babylon.max.js 4.3 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342763437634476345763467634776348763497635076351763527635376354763557635676357763587635976360763617636276363763647636576366763677636876369763707637176372763737637476375763767637776378763797638076381763827638376384763857638676387763887638976390763917639276393763947639576396763977639876399764007640176402764037640476405764067640776408764097641076411764127641376414764157641676417764187641976420764217642276423764247642576426764277642876429764307643176432764337643476435764367643776438764397644076441764427644376444764457644676447764487644976450764517645276453764547645576456764577645876459764607646176462764637646476465764667646776468764697647076471764727647376474764757647676477764787647976480764817648276483764847648576486764877648876489764907649176492764937649476495764967649776498764997650076501765027650376504765057650676507765087650976510765117651276513765147651576516765177651876519765207652176522765237652476525765267652776528765297653076531765327653376534765357653676537765387653976540765417654276543765447654576546765477654876549765507655176552765537655476555765567655776558765597656076561765627656376564765657656676567765687656976570765717657276573765747657576576765777657876579765807658176582765837658476585765867658776588765897659076591765927659376594765957659676597765987659976600766017660276603766047660576606766077660876609766107661176612766137661476615766167661776618766197662076621766227662376624766257662676627766287662976630766317663276633766347663576636766377663876639766407664176642766437664476645766467664776648766497665076651766527665376654766557665676657766587665976660766617666276663766647666576666766677666876669766707667176672766737667476675766767667776678766797668076681766827668376684766857668676687766887668976690766917669276693766947669576696766977669876699767007670176702767037670476705767067670776708767097671076711767127671376714767157671676717767187671976720767217672276723767247672576726767277672876729767307673176732767337673476735767367673776738767397674076741767427674376744767457674676747767487674976750767517675276753767547675576756767577675876759767607676176762767637676476765767667676776768767697677076771767727677376774767757677676777767787677976780767817678276783767847678576786767877678876789767907679176792767937679476795767967679776798767997680076801768027680376804768057680676807768087680976810768117681276813768147681576816768177681876819768207682176822768237682476825768267682776828768297683076831768327683376834768357683676837768387683976840768417684276843768447684576846768477684876849768507685176852768537685476855768567685776858768597686076861768627686376864768657686676867768687686976870768717687276873768747687576876768777687876879768807688176882768837688476885768867688776888768897689076891768927689376894768957689676897768987689976900769017690276903769047690576906769077690876909769107691176912769137691476915769167691776918769197692076921769227692376924769257692676927769287692976930769317693276933769347693576936769377693876939769407694176942769437694476945769467694776948769497695076951769527695376954769557695676957769587695976960769617696276963769647696576966769677696876969769707697176972769737697476975769767697776978769797698076981769827698376984769857698676987769887698976990769917699276993769947699576996769977699876999770007700177002770037700477005770067700777008770097701077011770127701377014770157701677017770187701977020770217702277023770247702577026770277702877029770307703177032770337703477035770367703777038770397704077041770427704377044770457704677047770487704977050770517705277053770547705577056770577705877059770607706177062770637706477065770667706777068770697707077071770727707377074770757707677077770787707977080770817708277083770847708577086770877708877089770907709177092770937709477095770967709777098770997710077101771027710377104771057710677107771087710977110771117711277113771147711577116771177711877119771207712177122771237712477125771267712777128771297713077131771327713377134771357713677137771387713977140771417714277143771447714577146771477714877149771507715177152771537715477155771567715777158771597716077161771627716377164771657716677167771687716977170771717717277173771747717577176771777717877179771807718177182771837718477185771867718777188771897719077191771927719377194771957719677197771987719977200772017720277203772047720577206772077720877209772107721177212772137721477215772167721777218772197722077221772227722377224772257722677227772287722977230772317723277233772347723577236772377723877239772407724177242772437724477245772467724777248772497725077251772527725377254772557725677257772587725977260772617726277263772647726577266772677726877269772707727177272772737727477275772767727777278772797728077281772827728377284772857728677287772887728977290772917729277293772947729577296772977729877299773007730177302773037730477305773067730777308773097731077311773127731377314773157731677317773187731977320773217732277323773247732577326773277732877329773307733177332773337733477335773367733777338773397734077341773427734377344773457734677347773487734977350773517735277353773547735577356773577735877359773607736177362773637736477365773667736777368773697737077371773727737377374773757737677377773787737977380773817738277383773847738577386773877738877389773907739177392773937739477395773967739777398773997740077401774027740377404774057740677407774087740977410774117741277413774147741577416774177741877419774207742177422774237742477425774267742777428774297743077431774327743377434774357743677437774387743977440774417744277443774447744577446774477744877449774507745177452774537745477455774567745777458774597746077461774627746377464774657746677467774687746977470774717747277473774747747577476774777747877479774807748177482774837748477485774867748777488774897749077491774927749377494774957749677497774987749977500775017750277503775047750577506775077750877509775107751177512775137751477515775167751777518775197752077521775227752377524775257752677527775287752977530775317753277533775347753577536775377753877539775407754177542775437754477545775467754777548775497755077551775527755377554775557755677557775587755977560775617756277563775647756577566775677756877569775707757177572775737757477575775767757777578775797758077581775827758377584775857758677587775887758977590775917759277593775947759577596775977759877599776007760177602776037760477605776067760777608776097761077611776127761377614776157761677617776187761977620776217762277623776247762577626776277762877629776307763177632776337763477635776367763777638776397764077641776427764377644776457764677647776487764977650776517765277653776547765577656776577765877659776607766177662776637766477665776667766777668776697767077671776727767377674776757767677677776787767977680776817768277683776847768577686776877768877689776907769177692776937769477695776967769777698776997770077701777027770377704777057770677707777087770977710777117771277713777147771577716777177771877719777207772177722777237772477725777267772777728777297773077731777327773377734777357773677737777387773977740777417774277743777447774577746777477774877749777507775177752777537775477755777567775777758777597776077761777627776377764777657776677767777687776977770777717777277773777747777577776777777777877779777807778177782777837778477785777867778777788777897779077791777927779377794777957779677797777987779977800778017780277803778047780577806778077780877809778107781177812778137781477815778167781777818778197782077821778227782377824778257782677827778287782977830778317783277833778347783577836778377783877839778407784177842778437784477845778467784777848778497785077851778527785377854778557785677857778587785977860778617786277863778647786577866778677786877869778707787177872778737787477875778767787777878778797788077881778827788377884778857788677887778887788977890778917789277893778947789577896778977789877899779007790177902779037790477905779067790777908779097791077911779127791377914779157791677917779187791977920779217792277923779247792577926779277792877929779307793177932779337793477935779367793777938779397794077941779427794377944779457794677947779487794977950779517795277953779547795577956779577795877959779607796177962779637796477965779667796777968779697797077971779727797377974779757797677977779787797977980779817798277983779847798577986779877798877989779907799177992779937799477995779967799777998779997800078001780027800378004780057800678007780087800978010780117801278013780147801578016780177801878019780207802178022780237802478025780267802778028780297803078031780327803378034780357803678037780387803978040780417804278043780447804578046780477804878049780507805178052780537805478055780567805778058780597806078061780627806378064780657806678067780687806978070780717807278073780747807578076780777807878079780807808178082780837808478085780867808778088780897809078091780927809378094780957809678097780987809978100781017810278103781047810578106781077810878109781107811178112781137811478115781167811778118781197812078121781227812378124781257812678127781287812978130781317813278133781347813578136781377813878139781407814178142781437814478145781467814778148781497815078151781527815378154781557815678157781587815978160781617816278163781647816578166781677816878169781707817178172781737817478175781767817778178781797818078181781827818378184781857818678187781887818978190781917819278193781947819578196781977819878199782007820178202782037820478205782067820778208782097821078211782127821378214782157821678217782187821978220782217822278223782247822578226782277822878229782307823178232782337823478235782367823778238782397824078241782427824378244782457824678247782487824978250782517825278253782547825578256782577825878259782607826178262782637826478265782667826778268782697827078271782727827378274782757827678277782787827978280782817828278283782847828578286782877828878289782907829178292782937829478295782967829778298782997830078301783027830378304783057830678307783087830978310783117831278313783147831578316783177831878319783207832178322783237832478325783267832778328783297833078331783327833378334783357833678337783387833978340783417834278343783447834578346783477834878349783507835178352783537835478355783567835778358783597836078361783627836378364783657836678367783687836978370783717837278373783747837578376783777837878379783807838178382783837838478385783867838778388783897839078391783927839378394783957839678397783987839978400784017840278403784047840578406784077840878409784107841178412784137841478415784167841778418784197842078421784227842378424784257842678427784287842978430784317843278433784347843578436784377843878439784407844178442784437844478445784467844778448784497845078451784527845378454784557845678457784587845978460784617846278463784647846578466784677846878469784707847178472784737847478475784767847778478784797848078481784827848378484784857848678487784887848978490784917849278493784947849578496784977849878499785007850178502785037850478505785067850778508785097851078511785127851378514785157851678517785187851978520785217852278523785247852578526785277852878529785307853178532785337853478535785367853778538785397854078541785427854378544785457854678547785487854978550785517855278553785547855578556785577855878559785607856178562785637856478565785667856778568785697857078571785727857378574785757857678577785787857978580785817858278583785847858578586785877858878589785907859178592785937859478595785967859778598785997860078601786027860378604786057860678607786087860978610786117861278613786147861578616786177861878619786207862178622786237862478625786267862778628786297863078631786327863378634786357863678637786387863978640786417864278643786447864578646786477864878649786507865178652786537865478655786567865778658786597866078661786627866378664786657866678667786687866978670786717867278673786747867578676786777867878679786807868178682786837868478685786867868778688786897869078691786927869378694786957869678697786987869978700787017870278703787047870578706787077870878709787107871178712787137871478715787167871778718787197872078721787227872378724787257872678727787287872978730787317873278733787347873578736787377873878739787407874178742787437874478745787467874778748787497875078751787527875378754787557875678757787587875978760787617876278763787647876578766787677876878769787707877178772787737877478775787767877778778787797878078781787827878378784787857878678787787887878978790787917879278793787947879578796787977879878799788007880178802788037880478805788067880778808788097881078811788127881378814788157881678817788187881978820788217882278823788247882578826788277882878829788307883178832788337883478835788367883778838788397884078841788427884378844788457884678847788487884978850788517885278853788547885578856788577885878859788607886178862788637886478865788667886778868788697887078871788727887378874788757887678877788787887978880788817888278883788847888578886788877888878889788907889178892788937889478895788967889778898788997890078901789027890378904789057890678907789087890978910789117891278913789147891578916789177891878919789207892178922789237892478925789267892778928789297893078931789327893378934789357893678937789387893978940789417894278943789447894578946789477894878949789507895178952789537895478955789567895778958789597896078961789627896378964789657896678967789687896978970789717897278973789747897578976789777897878979789807898178982789837898478985789867898778988789897899078991789927899378994789957899678997789987899979000790017900279003790047900579006790077900879009790107901179012790137901479015790167901779018790197902079021790227902379024790257902679027790287902979030790317903279033790347903579036790377903879039790407904179042790437904479045790467904779048790497905079051790527905379054790557905679057790587905979060790617906279063790647906579066790677906879069790707907179072790737907479075790767907779078790797908079081790827908379084790857908679087790887908979090790917909279093790947909579096790977909879099791007910179102791037910479105791067910779108791097911079111791127911379114791157911679117791187911979120791217912279123791247912579126791277912879129791307913179132791337913479135791367913779138791397914079141791427914379144791457914679147791487914979150791517915279153791547915579156791577915879159791607916179162791637916479165791667916779168791697917079171791727917379174791757917679177791787917979180791817918279183791847918579186791877918879189791907919179192791937919479195791967919779198791997920079201792027920379204792057920679207792087920979210792117921279213792147921579216792177921879219792207922179222792237922479225792267922779228792297923079231792327923379234792357923679237792387923979240792417924279243792447924579246792477924879249792507925179252792537925479255792567925779258792597926079261792627926379264792657926679267792687926979270792717927279273792747927579276792777927879279792807928179282792837928479285792867928779288792897929079291792927929379294792957929679297792987929979300793017930279303793047930579306793077930879309793107931179312793137931479315793167931779318793197932079321793227932379324793257932679327793287932979330793317933279333793347933579336793377933879339793407934179342793437934479345793467934779348793497935079351793527935379354793557935679357793587935979360793617936279363793647936579366793677936879369793707937179372793737937479375793767937779378793797938079381793827938379384793857938679387793887938979390793917939279393793947939579396793977939879399794007940179402794037940479405794067940779408794097941079411794127941379414794157941679417794187941979420794217942279423794247942579426794277942879429794307943179432794337943479435794367943779438794397944079441794427944379444794457944679447794487944979450794517945279453794547945579456794577945879459794607946179462794637946479465794667946779468794697947079471794727947379474794757947679477794787947979480794817948279483794847948579486794877948879489794907949179492794937949479495794967949779498794997950079501795027950379504795057950679507795087950979510795117951279513795147951579516795177951879519795207952179522795237952479525795267952779528795297953079531795327953379534795357953679537795387953979540795417954279543795447954579546795477954879549795507955179552795537955479555795567955779558795597956079561795627956379564795657956679567795687956979570795717957279573795747957579576795777957879579795807958179582795837958479585795867958779588795897959079591795927959379594795957959679597795987959979600796017960279603796047960579606796077960879609796107961179612796137961479615796167961779618796197962079621796227962379624796257962679627796287962979630796317963279633796347963579636796377963879639796407964179642796437964479645796467964779648796497965079651796527965379654796557965679657796587965979660796617966279663796647966579666796677966879669796707967179672796737967479675796767967779678796797968079681796827968379684796857968679687796887968979690796917969279693796947969579696796977969879699797007970179702797037970479705797067970779708797097971079711797127971379714797157971679717797187971979720797217972279723797247972579726797277972879729797307973179732797337973479735797367973779738797397974079741797427974379744797457974679747797487974979750797517975279753797547975579756797577975879759797607976179762797637976479765797667976779768797697977079771797727977379774797757977679777797787977979780797817978279783797847978579786797877978879789797907979179792797937979479795797967979779798797997980079801798027980379804798057980679807798087980979810798117981279813798147981579816798177981879819798207982179822798237982479825798267982779828798297983079831798327983379834798357983679837798387983979840798417984279843798447984579846798477984879849798507985179852798537985479855798567985779858798597986079861798627986379864798657986679867798687986979870798717987279873798747987579876798777987879879798807988179882798837988479885798867988779888798897989079891798927989379894798957989679897798987989979900799017990279903799047990579906799077990879909799107991179912799137991479915799167991779918799197992079921799227992379924799257992679927799287992979930799317993279933799347993579936799377993879939799407994179942799437994479945799467994779948799497995079951799527995379954799557995679957799587995979960799617996279963799647996579966799677996879969799707997179972799737997479975799767997779978799797998079981799827998379984799857998679987799887998979990799917999279993799947999579996799977999879999800008000180002800038000480005800068000780008800098001080011800128001380014800158001680017800188001980020800218002280023800248002580026800278002880029800308003180032800338003480035800368003780038800398004080041800428004380044800458004680047800488004980050800518005280053800548005580056800578005880059800608006180062800638006480065800668006780068800698007080071800728007380074800758007680077800788007980080800818008280083800848008580086800878008880089800908009180092800938009480095800968009780098800998010080101801028010380104801058010680107801088010980110801118011280113801148011580116801178011880119801208012180122801238012480125801268012780128801298013080131801328013380134801358013680137801388013980140801418014280143801448014580146801478014880149801508015180152801538015480155801568015780158801598016080161801628016380164801658016680167801688016980170801718017280173801748017580176801778017880179801808018180182801838018480185801868018780188801898019080191801928019380194801958019680197801988019980200802018020280203802048020580206802078020880209802108021180212802138021480215802168021780218802198022080221802228022380224802258022680227802288022980230802318023280233802348023580236802378023880239802408024180242802438024480245802468024780248802498025080251802528025380254802558025680257802588025980260802618026280263802648026580266802678026880269802708027180272802738027480275802768027780278802798028080281802828028380284802858028680287802888028980290802918029280293802948029580296802978029880299803008030180302803038030480305803068030780308803098031080311803128031380314803158031680317803188031980320803218032280323803248032580326803278032880329803308033180332803338033480335803368033780338803398034080341803428034380344803458034680347803488034980350803518035280353803548035580356803578035880359803608036180362803638036480365803668036780368803698037080371803728037380374803758037680377803788037980380803818038280383803848038580386803878038880389803908039180392803938039480395803968039780398803998040080401804028040380404804058040680407804088040980410804118041280413804148041580416804178041880419804208042180422804238042480425804268042780428804298043080431804328043380434804358043680437804388043980440804418044280443804448044580446804478044880449804508045180452804538045480455804568045780458804598046080461804628046380464804658046680467804688046980470804718047280473804748047580476804778047880479804808048180482804838048480485804868048780488804898049080491804928049380494804958049680497804988049980500805018050280503805048050580506805078050880509805108051180512805138051480515805168051780518805198052080521805228052380524805258052680527805288052980530805318053280533805348053580536805378053880539805408054180542805438054480545805468054780548805498055080551805528055380554805558055680557805588055980560805618056280563805648056580566805678056880569805708057180572805738057480575805768057780578805798058080581805828058380584805858058680587805888058980590805918059280593805948059580596805978059880599806008060180602806038060480605806068060780608806098061080611806128061380614806158061680617806188061980620806218062280623806248062580626806278062880629806308063180632806338063480635806368063780638806398064080641806428064380644806458064680647806488064980650806518065280653806548065580656806578065880659806608066180662806638066480665806668066780668806698067080671806728067380674806758067680677806788067980680806818068280683806848068580686806878068880689806908069180692806938069480695806968069780698806998070080701807028070380704807058070680707807088070980710807118071280713807148071580716807178071880719807208072180722807238072480725807268072780728807298073080731807328073380734807358073680737807388073980740807418074280743807448074580746807478074880749807508075180752807538075480755807568075780758807598076080761807628076380764807658076680767807688076980770807718077280773807748077580776807778077880779807808078180782807838078480785807868078780788807898079080791807928079380794807958079680797807988079980800808018080280803808048080580806808078080880809808108081180812808138081480815808168081780818808198082080821808228082380824808258082680827808288082980830808318083280833808348083580836808378083880839808408084180842808438084480845808468084780848808498085080851808528085380854808558085680857808588085980860808618086280863808648086580866808678086880869808708087180872808738087480875808768087780878808798088080881808828088380884808858088680887808888088980890808918089280893808948089580896808978089880899809008090180902809038090480905809068090780908809098091080911809128091380914809158091680917809188091980920809218092280923809248092580926809278092880929809308093180932809338093480935809368093780938809398094080941809428094380944809458094680947809488094980950809518095280953809548095580956809578095880959809608096180962809638096480965809668096780968809698097080971809728097380974809758097680977809788097980980809818098280983809848098580986809878098880989809908099180992809938099480995809968099780998809998100081001810028100381004810058100681007810088100981010810118101281013810148101581016810178101881019810208102181022810238102481025810268102781028810298103081031810328103381034810358103681037810388103981040810418104281043810448104581046810478104881049810508105181052810538105481055810568105781058810598106081061810628106381064810658106681067810688106981070810718107281073810748107581076810778107881079810808108181082810838108481085810868108781088810898109081091810928109381094810958109681097810988109981100811018110281103811048110581106811078110881109811108111181112811138111481115811168111781118811198112081121811228112381124811258112681127811288112981130811318113281133811348113581136811378113881139811408114181142811438114481145811468114781148811498115081151811528115381154811558115681157811588115981160811618116281163811648116581166811678116881169811708117181172811738117481175811768117781178811798118081181811828118381184811858118681187811888118981190811918119281193811948119581196811978119881199812008120181202812038120481205812068120781208812098121081211812128121381214812158121681217812188121981220812218122281223812248122581226812278122881229812308123181232812338123481235812368123781238812398124081241812428124381244812458124681247812488124981250812518125281253812548125581256812578125881259812608126181262812638126481265812668126781268812698127081271812728127381274812758127681277812788127981280812818128281283812848128581286812878128881289812908129181292812938129481295812968129781298812998130081301813028130381304813058130681307813088130981310813118131281313813148131581316813178131881319813208132181322813238132481325813268132781328813298133081331813328133381334813358133681337813388133981340813418134281343813448134581346813478134881349813508135181352813538135481355813568135781358813598136081361813628136381364813658136681367813688136981370813718137281373813748137581376813778137881379813808138181382813838138481385813868138781388813898139081391813928139381394813958139681397813988139981400814018140281403814048140581406814078140881409814108141181412814138141481415814168141781418814198142081421814228142381424814258142681427814288142981430814318143281433814348143581436814378143881439814408144181442814438144481445814468144781448814498145081451814528145381454814558145681457814588145981460814618146281463814648146581466814678146881469814708147181472814738147481475814768147781478814798148081481814828148381484814858148681487814888148981490814918149281493814948149581496814978149881499815008150181502815038150481505815068150781508815098151081511815128151381514815158151681517815188151981520815218152281523815248152581526815278152881529815308153181532815338153481535815368153781538815398154081541815428154381544815458154681547815488154981550815518155281553815548155581556815578155881559815608156181562815638156481565815668156781568815698157081571815728157381574815758157681577815788157981580815818158281583815848158581586815878158881589815908159181592815938159481595815968159781598815998160081601816028160381604816058160681607816088160981610816118161281613816148161581616816178161881619816208162181622816238162481625816268162781628816298163081631816328163381634816358163681637816388163981640816418164281643816448164581646816478164881649816508165181652816538165481655816568165781658816598166081661816628166381664816658166681667816688166981670816718167281673816748167581676816778167881679816808168181682816838168481685816868168781688816898169081691816928169381694816958169681697816988169981700817018170281703817048170581706817078170881709817108171181712817138171481715817168171781718817198172081721817228172381724817258172681727817288172981730817318173281733817348173581736817378173881739817408174181742817438174481745817468174781748817498175081751817528175381754817558175681757817588175981760817618176281763817648176581766817678176881769817708177181772817738177481775817768177781778817798178081781817828178381784817858178681787817888178981790817918179281793817948179581796817978179881799818008180181802818038180481805818068180781808818098181081811818128181381814818158181681817818188181981820818218182281823818248182581826818278182881829818308183181832818338183481835818368183781838818398184081841818428184381844818458184681847818488184981850818518185281853818548185581856818578185881859818608186181862818638186481865818668186781868818698187081871818728187381874818758187681877818788187981880818818188281883818848188581886818878188881889818908189181892818938189481895818968189781898818998190081901819028190381904819058190681907819088190981910819118191281913819148191581916819178191881919819208192181922819238192481925819268192781928819298193081931819328193381934819358193681937819388193981940819418194281943819448194581946819478194881949819508195181952819538195481955819568195781958819598196081961819628196381964819658196681967819688196981970819718197281973819748197581976819778197881979819808198181982819838198481985819868198781988819898199081991819928199381994819958199681997819988199982000820018200282003820048200582006820078200882009820108201182012820138201482015820168201782018820198202082021820228202382024820258202682027820288202982030820318203282033820348203582036820378203882039820408204182042820438204482045820468204782048820498205082051820528205382054820558205682057820588205982060820618206282063820648206582066820678206882069820708207182072820738207482075820768207782078820798208082081820828208382084820858208682087820888208982090820918209282093820948209582096820978209882099821008210182102821038210482105821068210782108821098211082111821128211382114821158211682117821188211982120821218212282123821248212582126821278212882129821308213182132821338213482135821368213782138821398214082141821428214382144821458214682147821488214982150821518215282153821548215582156821578215882159821608216182162821638216482165821668216782168821698217082171821728217382174821758217682177821788217982180821818218282183821848218582186821878218882189821908219182192821938219482195821968219782198821998220082201822028220382204822058220682207822088220982210822118221282213822148221582216822178221882219822208222182222822238222482225822268222782228822298223082231822328223382234822358223682237822388223982240822418224282243822448224582246822478224882249822508225182252822538225482255822568225782258822598226082261822628226382264822658226682267822688226982270822718227282273822748227582276822778227882279822808228182282822838228482285822868228782288822898229082291822928229382294822958229682297822988229982300823018230282303823048230582306823078230882309823108231182312823138231482315823168231782318823198232082321823228232382324823258232682327823288232982330823318233282333823348233582336823378233882339823408234182342823438234482345823468234782348823498235082351823528235382354823558235682357823588235982360823618236282363823648236582366823678236882369823708237182372823738237482375823768237782378823798238082381823828238382384823858238682387823888238982390823918239282393823948239582396823978239882399824008240182402824038240482405824068240782408824098241082411824128241382414824158241682417824188241982420824218242282423824248242582426824278242882429824308243182432824338243482435824368243782438824398244082441824428244382444824458244682447824488244982450824518245282453824548245582456824578245882459824608246182462824638246482465824668246782468824698247082471824728247382474824758247682477824788247982480824818248282483824848248582486824878248882489824908249182492824938249482495824968249782498824998250082501825028250382504825058250682507825088250982510825118251282513825148251582516825178251882519825208252182522825238252482525825268252782528825298253082531825328253382534825358253682537825388253982540825418254282543825448254582546825478254882549825508255182552825538255482555825568255782558825598256082561825628256382564825658256682567825688256982570825718257282573825748257582576825778257882579825808258182582825838258482585825868258782588825898259082591825928259382594825958259682597825988259982600826018260282603826048260582606826078260882609826108261182612826138261482615826168261782618826198262082621826228262382624826258262682627826288262982630826318263282633826348263582636826378263882639826408264182642826438264482645826468264782648826498265082651826528265382654826558265682657826588265982660826618266282663826648266582666826678266882669826708267182672826738267482675826768267782678826798268082681826828268382684826858268682687826888268982690826918269282693826948269582696826978269882699827008270182702827038270482705827068270782708827098271082711827128271382714827158271682717827188271982720827218272282723827248272582726827278272882729827308273182732827338273482735827368273782738827398274082741827428274382744827458274682747827488274982750827518275282753827548275582756827578275882759827608276182762827638276482765827668276782768827698277082771827728277382774827758277682777827788277982780827818278282783827848278582786827878278882789827908279182792827938279482795827968279782798827998280082801828028280382804828058280682807828088280982810828118281282813828148281582816828178281882819828208282182822828238282482825828268282782828828298283082831828328283382834828358283682837828388283982840828418284282843828448284582846828478284882849828508285182852828538285482855828568285782858828598286082861828628286382864828658286682867828688286982870828718287282873828748287582876828778287882879828808288182882828838288482885828868288782888828898289082891828928289382894828958289682897828988289982900829018290282903829048290582906829078290882909829108291182912829138291482915829168291782918829198292082921829228292382924829258292682927829288292982930829318293282933829348293582936829378293882939829408294182942829438294482945829468294782948829498295082951829528295382954829558295682957829588295982960829618296282963829648296582966829678296882969829708297182972829738297482975829768297782978829798298082981829828298382984829858298682987829888298982990829918299282993829948299582996829978299882999830008300183002830038300483005830068300783008830098301083011830128301383014830158301683017830188301983020830218302283023830248302583026830278302883029830308303183032830338303483035830368303783038830398304083041830428304383044830458304683047830488304983050830518305283053830548305583056830578305883059830608306183062830638306483065830668306783068830698307083071830728307383074830758307683077830788307983080830818308283083830848308583086830878308883089830908309183092830938309483095830968309783098830998310083101831028310383104831058310683107831088310983110831118311283113831148311583116831178311883119831208312183122831238312483125831268312783128831298313083131831328313383134831358313683137831388313983140831418314283143831448314583146831478314883149831508315183152831538315483155831568315783158831598316083161831628316383164831658316683167831688316983170831718317283173831748317583176831778317883179831808318183182831838318483185831868318783188831898319083191831928319383194831958319683197831988319983200832018320283203832048320583206832078320883209832108321183212832138321483215832168321783218832198322083221832228322383224832258322683227832288322983230832318323283233832348323583236832378323883239832408324183242832438324483245832468324783248832498325083251832528325383254832558325683257832588325983260832618326283263832648326583266832678326883269832708327183272832738327483275832768327783278832798328083281832828328383284832858328683287832888328983290832918329283293832948329583296832978329883299833008330183302833038330483305833068330783308833098331083311833128331383314833158331683317833188331983320833218332283323833248332583326833278332883329833308333183332833338333483335833368333783338833398334083341833428334383344833458334683347833488334983350833518335283353833548335583356833578335883359833608336183362833638336483365833668336783368833698337083371833728337383374833758337683377833788337983380833818338283383833848338583386833878338883389833908339183392833938339483395833968339783398833998340083401834028340383404834058340683407834088340983410834118341283413834148341583416834178341883419834208342183422834238342483425834268342783428834298343083431834328343383434834358343683437834388343983440834418344283443834448344583446834478344883449834508345183452834538345483455834568345783458834598346083461834628346383464834658346683467834688346983470834718347283473834748347583476834778347883479834808348183482834838348483485834868348783488834898349083491834928349383494834958349683497834988349983500835018350283503835048350583506835078350883509835108351183512835138351483515835168351783518835198352083521835228352383524835258352683527835288352983530835318353283533835348353583536835378353883539835408354183542835438354483545835468354783548835498355083551835528355383554835558355683557835588355983560835618356283563835648356583566835678356883569835708357183572835738357483575835768357783578835798358083581835828358383584835858358683587835888358983590835918359283593835948359583596835978359883599836008360183602836038360483605836068360783608836098361083611836128361383614836158361683617836188361983620836218362283623836248362583626836278362883629836308363183632836338363483635836368363783638836398364083641836428364383644836458364683647836488364983650836518365283653836548365583656836578365883659836608366183662836638366483665836668366783668836698367083671836728367383674836758367683677836788367983680836818368283683836848368583686836878368883689836908369183692836938369483695836968369783698836998370083701837028370383704837058370683707837088370983710837118371283713837148371583716837178371883719837208372183722837238372483725837268372783728837298373083731837328373383734837358373683737837388373983740837418374283743837448374583746837478374883749837508375183752837538375483755837568375783758837598376083761837628376383764837658376683767837688376983770837718377283773837748377583776837778377883779837808378183782837838378483785837868378783788837898379083791837928379383794837958379683797837988379983800838018380283803838048380583806838078380883809838108381183812838138381483815838168381783818838198382083821838228382383824838258382683827838288382983830838318383283833838348383583836838378383883839838408384183842838438384483845838468384783848838498385083851838528385383854838558385683857838588385983860838618386283863838648386583866838678386883869838708387183872838738387483875838768387783878838798388083881838828388383884838858388683887838888388983890838918389283893838948389583896838978389883899839008390183902839038390483905839068390783908839098391083911839128391383914839158391683917839188391983920839218392283923839248392583926839278392883929839308393183932839338393483935839368393783938839398394083941839428394383944839458394683947839488394983950839518395283953839548395583956839578395883959839608396183962839638396483965839668396783968839698397083971839728397383974839758397683977839788397983980839818398283983839848398583986839878398883989839908399183992839938399483995839968399783998839998400084001840028400384004840058400684007840088400984010840118401284013840148401584016840178401884019840208402184022840238402484025840268402784028840298403084031840328403384034840358403684037840388403984040840418404284043840448404584046840478404884049840508405184052840538405484055840568405784058840598406084061840628406384064840658406684067840688406984070840718407284073840748407584076840778407884079840808408184082840838408484085840868408784088840898409084091840928409384094840958409684097840988409984100841018410284103841048410584106841078410884109841108411184112841138411484115841168411784118841198412084121841228412384124841258412684127841288412984130841318413284133841348413584136841378413884139841408414184142841438414484145841468414784148841498415084151841528415384154841558415684157841588415984160841618416284163841648416584166841678416884169841708417184172841738417484175841768417784178841798418084181841828418384184841858418684187841888418984190841918419284193841948419584196841978419884199842008420184202842038420484205842068420784208842098421084211842128421384214842158421684217842188421984220842218422284223842248422584226842278422884229842308423184232842338423484235842368423784238842398424084241842428424384244842458424684247842488424984250842518425284253842548425584256842578425884259842608426184262842638426484265842668426784268842698427084271842728427384274842758427684277842788427984280842818428284283842848428584286842878428884289842908429184292842938429484295842968429784298842998430084301843028430384304843058430684307843088430984310843118431284313843148431584316843178431884319843208432184322843238432484325843268432784328843298433084331843328433384334843358433684337843388433984340843418434284343843448434584346843478434884349843508435184352843538435484355843568435784358843598436084361843628436384364843658436684367843688436984370843718437284373843748437584376843778437884379843808438184382843838438484385843868438784388843898439084391843928439384394843958439684397843988439984400844018440284403844048440584406844078440884409844108441184412844138441484415844168441784418844198442084421844228442384424844258442684427844288442984430844318443284433844348443584436844378443884439844408444184442844438444484445844468444784448844498445084451844528445384454844558445684457844588445984460844618446284463844648446584466844678446884469844708447184472844738447484475844768447784478844798448084481844828448384484844858448684487844888448984490844918449284493844948449584496844978449884499845008450184502845038450484505845068450784508845098451084511845128451384514845158451684517845188451984520845218452284523845248452584526845278452884529845308453184532845338453484535845368453784538845398454084541845428454384544845458454684547845488454984550845518455284553845548455584556845578455884559845608456184562845638456484565845668456784568845698457084571845728457384574845758457684577845788457984580845818458284583845848458584586845878458884589845908459184592845938459484595845968459784598845998460084601846028460384604846058460684607846088460984610846118461284613846148461584616846178461884619846208462184622846238462484625846268462784628846298463084631846328463384634846358463684637846388463984640846418464284643846448464584646846478464884649846508465184652846538465484655846568465784658846598466084661846628466384664846658466684667846688466984670846718467284673846748467584676846778467884679846808468184682846838468484685846868468784688846898469084691846928469384694846958469684697846988469984700847018470284703847048470584706847078470884709847108471184712847138471484715847168471784718847198472084721847228472384724847258472684727847288472984730847318473284733847348473584736847378473884739847408474184742847438474484745847468474784748847498475084751847528475384754847558475684757847588475984760847618476284763847648476584766847678476884769847708477184772847738477484775847768477784778847798478084781847828478384784847858478684787847888478984790847918479284793847948479584796847978479884799848008480184802848038480484805848068480784808848098481084811848128481384814848158481684817848188481984820848218482284823848248482584826848278482884829848308483184832848338483484835848368483784838848398484084841848428484384844848458484684847848488484984850848518485284853848548485584856848578485884859848608486184862848638486484865848668486784868848698487084871848728487384874848758487684877848788487984880848818488284883848848488584886848878488884889848908489184892848938489484895848968489784898848998490084901849028490384904849058490684907849088490984910849118491284913849148491584916849178491884919849208492184922849238492484925849268492784928849298493084931849328493384934849358493684937849388493984940849418494284943849448494584946849478494884949849508495184952849538495484955849568495784958849598496084961849628496384964849658496684967849688496984970849718497284973849748497584976849778497884979849808498184982849838498484985849868498784988849898499084991849928499384994849958499684997849988499985000850018500285003850048500585006850078500885009850108501185012850138501485015850168501785018850198502085021850228502385024850258502685027850288502985030850318503285033850348503585036850378503885039850408504185042850438504485045850468504785048850498505085051850528505385054850558505685057850588505985060850618506285063850648506585066850678506885069850708507185072850738507485075850768507785078850798508085081850828508385084850858508685087850888508985090850918509285093850948509585096850978509885099851008510185102851038510485105851068510785108851098511085111851128511385114851158511685117851188511985120851218512285123851248512585126851278512885129851308513185132851338513485135851368513785138851398514085141851428514385144851458514685147851488514985150851518515285153851548515585156851578515885159851608516185162851638516485165851668516785168851698517085171851728517385174851758517685177851788517985180851818518285183851848518585186851878518885189851908519185192851938519485195851968519785198851998520085201852028520385204852058520685207852088520985210852118521285213852148521585216852178521885219852208522185222852238522485225852268522785228852298523085231852328523385234852358523685237852388523985240852418524285243852448524585246852478524885249852508525185252852538525485255852568525785258852598526085261852628526385264852658526685267852688526985270852718527285273852748527585276852778527885279852808528185282852838528485285852868528785288852898529085291852928529385294852958529685297852988529985300853018530285303853048530585306853078530885309853108531185312853138531485315853168531785318853198532085321853228532385324853258532685327853288532985330853318533285333853348533585336853378533885339853408534185342853438534485345853468534785348853498535085351853528535385354853558535685357853588535985360853618536285363853648536585366853678536885369853708537185372853738537485375853768537785378853798538085381853828538385384853858538685387853888538985390853918539285393853948539585396853978539885399854008540185402854038540485405854068540785408854098541085411854128541385414854158541685417854188541985420854218542285423854248542585426854278542885429854308543185432854338543485435854368543785438854398544085441854428544385444854458544685447854488544985450854518545285453854548545585456854578545885459854608546185462854638546485465854668546785468854698547085471854728547385474854758547685477854788547985480854818548285483854848548585486854878548885489854908549185492854938549485495854968549785498854998550085501855028550385504855058550685507855088550985510855118551285513855148551585516855178551885519855208552185522855238552485525855268552785528855298553085531855328553385534855358553685537855388553985540855418554285543855448554585546855478554885549855508555185552855538555485555855568555785558855598556085561855628556385564855658556685567855688556985570855718557285573855748557585576855778557885579855808558185582855838558485585855868558785588855898559085591855928559385594855958559685597855988559985600856018560285603856048560585606856078560885609856108561185612856138561485615856168561785618856198562085621856228562385624856258562685627856288562985630856318563285633856348563585636856378563885639856408564185642856438564485645856468564785648856498565085651856528565385654856558565685657856588565985660856618566285663856648566585666856678566885669856708567185672856738567485675856768567785678856798568085681856828568385684856858568685687856888568985690856918569285693856948569585696856978569885699857008570185702857038570485705857068570785708857098571085711857128571385714857158571685717857188571985720857218572285723857248572585726857278572885729857308573185732857338573485735857368573785738857398574085741857428574385744857458574685747857488574985750857518575285753857548575585756857578575885759857608576185762857638576485765857668576785768857698577085771857728577385774857758577685777857788577985780857818578285783857848578585786857878578885789857908579185792857938579485795857968579785798857998580085801858028580385804858058580685807858088580985810858118581285813858148581585816858178581885819858208582185822858238582485825858268582785828858298583085831858328583385834858358583685837858388583985840858418584285843858448584585846858478584885849858508585185852858538585485855858568585785858858598586085861858628586385864858658586685867858688586985870858718587285873858748587585876858778587885879858808588185882858838588485885858868588785888858898589085891858928589385894858958589685897858988589985900859018590285903859048590585906859078590885909859108591185912859138591485915859168591785918859198592085921859228592385924859258592685927859288592985930859318593285933859348593585936859378593885939859408594185942859438594485945859468594785948859498595085951859528595385954859558595685957859588595985960859618596285963859648596585966859678596885969859708597185972859738597485975859768597785978859798598085981859828598385984859858598685987859888598985990859918599285993859948599585996859978599885999860008600186002860038600486005860068600786008860098601086011860128601386014860158601686017860188601986020860218602286023860248602586026860278602886029860308603186032860338603486035860368603786038860398604086041860428604386044860458604686047860488604986050860518605286053860548605586056860578605886059860608606186062860638606486065860668606786068860698607086071860728607386074860758607686077860788607986080860818608286083860848608586086860878608886089860908609186092860938609486095860968609786098860998610086101861028610386104861058610686107861088610986110861118611286113861148611586116861178611886119861208612186122861238612486125861268612786128861298613086131861328613386134861358613686137861388613986140861418614286143861448614586146861478614886149861508615186152861538615486155861568615786158861598616086161861628616386164861658616686167861688616986170861718617286173861748617586176861778617886179861808618186182861838618486185861868618786188861898619086191861928619386194861958619686197861988619986200862018620286203862048620586206862078620886209862108621186212862138621486215862168621786218862198622086221862228622386224862258622686227862288622986230862318623286233862348623586236862378623886239862408624186242862438624486245862468624786248862498625086251862528625386254862558625686257862588625986260862618626286263862648626586266862678626886269862708627186272862738627486275862768627786278862798628086281862828628386284862858628686287862888628986290862918629286293862948629586296862978629886299863008630186302863038630486305863068630786308863098631086311863128631386314863158631686317863188631986320863218632286323863248632586326863278632886329863308633186332863338633486335863368633786338863398634086341863428634386344863458634686347863488634986350863518635286353863548635586356863578635886359863608636186362863638636486365863668636786368863698637086371863728637386374863758637686377863788637986380863818638286383863848638586386863878638886389863908639186392863938639486395863968639786398863998640086401864028640386404864058640686407864088640986410864118641286413864148641586416864178641886419864208642186422864238642486425864268642786428864298643086431864328643386434864358643686437864388643986440864418644286443864448644586446864478644886449864508645186452864538645486455864568645786458864598646086461864628646386464864658646686467864688646986470864718647286473864748647586476864778647886479864808648186482864838648486485864868648786488864898649086491864928649386494864958649686497864988649986500865018650286503865048650586506865078650886509865108651186512865138651486515865168651786518865198652086521865228652386524865258652686527865288652986530865318653286533865348653586536865378653886539865408654186542865438654486545865468654786548865498655086551865528655386554865558655686557865588655986560865618656286563865648656586566865678656886569865708657186572865738657486575865768657786578865798658086581865828658386584865858658686587865888658986590865918659286593865948659586596865978659886599866008660186602866038660486605866068660786608866098661086611866128661386614866158661686617866188661986620866218662286623866248662586626866278662886629866308663186632866338663486635866368663786638866398664086641866428664386644866458664686647866488664986650866518665286653866548665586656866578665886659866608666186662866638666486665866668666786668866698667086671866728667386674866758667686677866788667986680866818668286683866848668586686866878668886689866908669186692866938669486695866968669786698866998670086701867028670386704867058670686707867088670986710867118671286713867148671586716867178671886719867208672186722867238672486725867268672786728867298673086731867328673386734867358673686737867388673986740867418674286743867448674586746867478674886749867508675186752867538675486755867568675786758867598676086761867628676386764867658676686767867688676986770867718677286773867748677586776867778677886779867808678186782867838678486785867868678786788867898679086791867928679386794867958679686797867988679986800868018680286803868048680586806868078680886809868108681186812868138681486815868168681786818868198682086821868228682386824868258682686827868288682986830868318683286833868348683586836868378683886839868408684186842868438684486845868468684786848868498685086851868528685386854868558685686857868588685986860868618686286863868648686586866868678686886869868708687186872868738687486875868768687786878868798688086881868828688386884868858688686887868888688986890868918689286893868948689586896868978689886899869008690186902869038690486905869068690786908869098691086911869128691386914869158691686917869188691986920869218692286923869248692586926869278692886929869308693186932869338693486935869368693786938869398694086941869428694386944869458694686947869488694986950869518695286953869548695586956869578695886959869608696186962869638696486965869668696786968869698697086971869728697386974869758697686977869788697986980869818698286983869848698586986869878698886989869908699186992869938699486995869968699786998869998700087001870028700387004870058700687007870088700987010870118701287013870148701587016870178701887019870208702187022870238702487025870268702787028870298703087031870328703387034870358703687037870388703987040870418704287043870448704587046870478704887049870508705187052870538705487055870568705787058870598706087061870628706387064870658706687067870688706987070870718707287073870748707587076870778707887079870808708187082870838708487085870868708787088870898709087091870928709387094870958709687097870988709987100871018710287103871048710587106871078710887109871108711187112871138711487115871168711787118871198712087121871228712387124871258712687127871288712987130871318713287133871348713587136871378713887139871408714187142871438714487145871468714787148871498715087151871528715387154871558715687157871588715987160871618716287163871648716587166871678716887169871708717187172871738717487175871768717787178871798718087181871828718387184871858718687187871888718987190871918719287193871948719587196871978719887199872008720187202872038720487205872068720787208872098721087211872128721387214872158721687217872188721987220872218722287223872248722587226872278722887229872308723187232872338723487235872368723787238872398724087241872428724387244872458724687247872488724987250872518725287253872548725587256872578725887259872608726187262872638726487265872668726787268872698727087271872728727387274872758727687277872788727987280872818728287283872848728587286872878728887289872908729187292872938729487295872968729787298872998730087301873028730387304873058730687307873088730987310873118731287313873148731587316873178731887319873208732187322873238732487325873268732787328873298733087331873328733387334873358733687337873388733987340873418734287343873448734587346873478734887349873508735187352873538735487355873568735787358873598736087361873628736387364873658736687367873688736987370873718737287373873748737587376873778737887379873808738187382873838738487385873868738787388873898739087391873928739387394873958739687397873988739987400874018740287403874048740587406874078740887409874108741187412874138741487415874168741787418874198742087421874228742387424874258742687427874288742987430874318743287433874348743587436874378743887439874408744187442874438744487445874468744787448874498745087451874528745387454874558745687457874588745987460874618746287463874648746587466874678746887469874708747187472874738747487475874768747787478874798748087481874828748387484874858748687487874888748987490874918749287493874948749587496874978749887499875008750187502875038750487505875068750787508875098751087511875128751387514875158751687517875188751987520875218752287523875248752587526875278752887529875308753187532875338753487535875368753787538875398754087541875428754387544875458754687547875488754987550875518755287553875548755587556875578755887559875608756187562875638756487565875668756787568875698757087571875728757387574875758757687577875788757987580875818758287583875848758587586875878758887589875908759187592875938759487595875968759787598875998760087601876028760387604876058760687607876088760987610876118761287613876148761587616876178761887619876208762187622876238762487625876268762787628876298763087631876328763387634876358763687637876388763987640876418764287643876448764587646876478764887649876508765187652876538765487655876568765787658876598766087661876628766387664876658766687667876688766987670876718767287673876748767587676876778767887679876808768187682876838768487685876868768787688876898769087691876928769387694876958769687697876988769987700877018770287703877048770587706877078770887709877108771187712877138771487715877168771787718877198772087721877228772387724877258772687727877288772987730877318773287733877348773587736877378773887739877408774187742877438774487745877468774787748877498775087751877528775387754877558775687757877588775987760877618776287763877648776587766877678776887769877708777187772877738777487775877768777787778877798778087781877828778387784877858778687787877888778987790877918779287793877948779587796877978779887799878008780187802878038780487805878068780787808878098781087811878128781387814878158781687817878188781987820878218782287823878248782587826878278782887829878308783187832878338783487835878368783787838878398784087841878428784387844878458784687847878488784987850878518785287853878548785587856878578785887859878608786187862878638786487865878668786787868878698787087871878728787387874878758787687877878788787987880878818788287883878848788587886878878788887889878908789187892878938789487895878968789787898878998790087901879028790387904879058790687907879088790987910879118791287913879148791587916879178791887919879208792187922879238792487925879268792787928879298793087931879328793387934879358793687937879388793987940879418794287943879448794587946879478794887949879508795187952879538795487955879568795787958879598796087961879628796387964879658796687967879688796987970879718797287973879748797587976879778797887979879808798187982879838798487985879868798787988879898799087991879928799387994879958799687997879988799988000880018800288003880048800588006880078800888009880108801188012880138801488015880168801788018880198802088021880228802388024880258802688027880288802988030880318803288033880348803588036880378803888039880408804188042880438804488045880468804788048880498805088051880528805388054880558805688057880588805988060880618806288063880648806588066880678806888069880708807188072880738807488075880768807788078880798808088081880828808388084880858808688087880888808988090880918809288093880948809588096880978809888099881008810188102881038810488105881068810788108881098811088111881128811388114881158811688117881188811988120881218812288123881248812588126881278812888129881308813188132881338813488135881368813788138881398814088141881428814388144881458814688147881488814988150881518815288153881548815588156881578815888159881608816188162881638816488165881668816788168881698817088171881728817388174881758817688177881788817988180881818818288183881848818588186881878818888189881908819188192881938819488195881968819788198881998820088201882028820388204882058820688207882088820988210882118821288213882148821588216882178821888219882208822188222882238822488225882268822788228882298823088231882328823388234882358823688237882388823988240882418824288243882448824588246882478824888249882508825188252882538825488255882568825788258882598826088261882628826388264882658826688267882688826988270882718827288273882748827588276882778827888279882808828188282882838828488285882868828788288882898829088291882928829388294882958829688297882988829988300883018830288303883048830588306883078830888309883108831188312883138831488315883168831788318883198832088321883228832388324883258832688327883288832988330883318833288333883348833588336883378833888339883408834188342883438834488345883468834788348883498835088351883528835388354883558835688357883588835988360883618836288363883648836588366883678836888369883708837188372883738837488375883768837788378883798838088381883828838388384883858838688387883888838988390883918839288393883948839588396883978839888399884008840188402884038840488405884068840788408884098841088411884128841388414884158841688417884188841988420884218842288423884248842588426884278842888429884308843188432884338843488435884368843788438884398844088441884428844388444884458844688447884488844988450884518845288453884548845588456884578845888459884608846188462884638846488465884668846788468884698847088471884728847388474884758847688477884788847988480884818848288483884848848588486884878848888489884908849188492884938849488495884968849788498884998850088501885028850388504885058850688507885088850988510885118851288513885148851588516885178851888519885208852188522885238852488525885268852788528885298853088531885328853388534885358853688537885388853988540885418854288543885448854588546885478854888549885508855188552885538855488555885568855788558885598856088561885628856388564885658856688567885688856988570885718857288573885748857588576885778857888579885808858188582885838858488585885868858788588885898859088591885928859388594885958859688597885988859988600886018860288603886048860588606886078860888609886108861188612886138861488615886168861788618886198862088621886228862388624886258862688627886288862988630886318863288633886348863588636886378863888639886408864188642886438864488645886468864788648886498865088651886528865388654886558865688657886588865988660886618866288663886648866588666886678866888669886708867188672886738867488675886768867788678886798868088681886828868388684886858868688687886888868988690886918869288693886948869588696886978869888699887008870188702887038870488705887068870788708887098871088711887128871388714887158871688717887188871988720887218872288723887248872588726887278872888729887308873188732887338873488735887368873788738887398874088741887428874388744887458874688747887488874988750887518875288753887548875588756887578875888759887608876188762887638876488765887668876788768887698877088771887728877388774887758877688777887788877988780887818878288783887848878588786887878878888789887908879188792887938879488795887968879788798887998880088801888028880388804888058880688807888088880988810888118881288813888148881588816888178881888819888208882188822888238882488825888268882788828888298883088831888328883388834888358883688837888388883988840888418884288843888448884588846888478884888849888508885188852888538885488855888568885788858888598886088861888628886388864888658886688867888688886988870888718887288873888748887588876888778887888879888808888188882888838888488885888868888788888888898889088891888928889388894888958889688897888988889988900889018890288903889048890588906889078890888909889108891188912889138891488915889168891788918889198892088921889228892388924889258892688927889288892988930889318893288933889348893588936889378893888939889408894188942889438894488945889468894788948889498895088951889528895388954889558895688957889588895988960889618896288963889648896588966889678896888969889708897188972889738897488975889768897788978889798898088981889828898388984889858898688987889888898988990889918899288993889948899588996889978899888999890008900189002890038900489005890068900789008890098901089011890128901389014890158901689017890188901989020890218902289023890248902589026890278902889029890308903189032890338903489035890368903789038890398904089041890428904389044890458904689047890488904989050890518905289053890548905589056890578905889059890608906189062890638906489065890668906789068890698907089071890728907389074890758907689077890788907989080890818908289083890848908589086890878908889089890908909189092890938909489095890968909789098890998910089101891028910389104891058910689107891088910989110891118911289113891148911589116891178911889119891208912189122891238912489125891268912789128891298913089131891328913389134891358913689137891388913989140891418914289143891448914589146891478914889149891508915189152891538915489155891568915789158891598916089161891628916389164891658916689167891688916989170891718917289173891748917589176891778917889179891808918189182891838918489185891868918789188891898919089191891928919389194891958919689197891988919989200892018920289203892048920589206892078920889209892108921189212892138921489215892168921789218892198922089221892228922389224892258922689227892288922989230892318923289233892348923589236892378923889239892408924189242892438924489245892468924789248892498925089251892528925389254892558925689257892588925989260892618926289263892648926589266892678926889269892708927189272892738927489275892768927789278892798928089281892828928389284892858928689287892888928989290892918929289293892948929589296892978929889299893008930189302893038930489305893068930789308893098931089311893128931389314893158931689317893188931989320893218932289323893248932589326893278932889329893308933189332893338933489335893368933789338893398934089341893428934389344893458934689347893488934989350893518935289353893548935589356893578935889359893608936189362893638936489365893668936789368893698937089371893728937389374893758937689377893788937989380893818938289383893848938589386893878938889389893908939189392893938939489395893968939789398893998940089401894028940389404894058940689407894088940989410894118941289413894148941589416894178941889419894208942189422894238942489425894268942789428894298943089431894328943389434894358943689437894388943989440894418944289443894448944589446894478944889449894508945189452894538945489455894568945789458894598946089461894628946389464894658946689467894688946989470894718947289473894748947589476894778947889479894808948189482894838948489485894868948789488894898949089491894928949389494894958949689497894988949989500895018950289503895048950589506895078950889509895108951189512895138951489515895168951789518895198952089521895228952389524895258952689527895288952989530895318953289533895348953589536895378953889539895408954189542895438954489545895468954789548895498955089551895528955389554895558955689557895588955989560895618956289563895648956589566895678956889569895708957189572895738957489575895768957789578895798958089581895828958389584895858958689587895888958989590895918959289593895948959589596895978959889599896008960189602896038960489605896068960789608896098961089611896128961389614896158961689617896188961989620896218962289623896248962589626896278962889629896308963189632896338963489635896368963789638896398964089641
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || (function () {
  8. var extendStatics = Object.setPrototypeOf ||
  9. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  10. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  11. return function (d, b) {
  12. extendStatics(d, b);
  13. function __() { this.constructor = d; }
  14. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  15. };
  16. })();
  17. var BABYLON;
  18. (function (BABYLON) {
  19. var EffectFallbacks = /** @class */ (function () {
  20. function EffectFallbacks() {
  21. this._defines = {};
  22. this._currentRank = 32;
  23. this._maxRank = -1;
  24. }
  25. EffectFallbacks.prototype.unBindMesh = function () {
  26. this._mesh = null;
  27. };
  28. EffectFallbacks.prototype.addFallback = function (rank, define) {
  29. if (!this._defines[rank]) {
  30. if (rank < this._currentRank) {
  31. this._currentRank = rank;
  32. }
  33. if (rank > this._maxRank) {
  34. this._maxRank = rank;
  35. }
  36. this._defines[rank] = new Array();
  37. }
  38. this._defines[rank].push(define);
  39. };
  40. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  41. this._mesh = mesh;
  42. if (rank < this._currentRank) {
  43. this._currentRank = rank;
  44. }
  45. if (rank > this._maxRank) {
  46. this._maxRank = rank;
  47. }
  48. };
  49. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  50. get: function () {
  51. return this._currentRank <= this._maxRank;
  52. },
  53. enumerable: true,
  54. configurable: true
  55. });
  56. EffectFallbacks.prototype.reduce = function (currentDefines) {
  57. // First we try to switch to CPU skinning
  58. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  59. this._mesh.computeBonesUsingShaders = false;
  60. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  61. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  62. var scene = this._mesh.getScene();
  63. for (var index = 0; index < scene.meshes.length; index++) {
  64. var otherMesh = scene.meshes[index];
  65. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  66. otherMesh.computeBonesUsingShaders = false;
  67. }
  68. }
  69. }
  70. else {
  71. var currentFallbacks = this._defines[this._currentRank];
  72. if (currentFallbacks) {
  73. for (var index = 0; index < currentFallbacks.length; index++) {
  74. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  75. }
  76. }
  77. this._currentRank++;
  78. }
  79. return currentDefines;
  80. };
  81. return EffectFallbacks;
  82. }());
  83. BABYLON.EffectFallbacks = EffectFallbacks;
  84. var EffectCreationOptions = /** @class */ (function () {
  85. function EffectCreationOptions() {
  86. }
  87. return EffectCreationOptions;
  88. }());
  89. BABYLON.EffectCreationOptions = EffectCreationOptions;
  90. var Effect = /** @class */ (function () {
  91. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  92. if (samplers === void 0) { samplers = null; }
  93. if (defines === void 0) { defines = null; }
  94. if (fallbacks === void 0) { fallbacks = null; }
  95. if (onCompiled === void 0) { onCompiled = null; }
  96. if (onError === void 0) { onError = null; }
  97. var _this = this;
  98. this.uniqueId = 0;
  99. this.onCompileObservable = new BABYLON.Observable();
  100. this.onErrorObservable = new BABYLON.Observable();
  101. this.onBindObservable = new BABYLON.Observable();
  102. this._uniformBuffersNames = {};
  103. this._isReady = false;
  104. this._compilationError = "";
  105. this.name = baseName;
  106. if (attributesNamesOrOptions.attributes) {
  107. var options = attributesNamesOrOptions;
  108. this._engine = uniformsNamesOrEngine;
  109. this._attributesNames = options.attributes;
  110. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  111. this._samplers = options.samplers;
  112. this.defines = options.defines;
  113. this.onError = options.onError;
  114. this.onCompiled = options.onCompiled;
  115. this._fallbacks = options.fallbacks;
  116. this._indexParameters = options.indexParameters;
  117. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  118. if (options.uniformBuffersNames) {
  119. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  120. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  121. }
  122. }
  123. }
  124. else {
  125. this._engine = engine;
  126. this.defines = defines;
  127. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  128. this._samplers = samplers;
  129. this._attributesNames = attributesNamesOrOptions;
  130. this.onError = onError;
  131. this.onCompiled = onCompiled;
  132. this._indexParameters = indexParameters;
  133. this._fallbacks = fallbacks;
  134. }
  135. this.uniqueId = Effect._uniqueIdSeed++;
  136. var vertexSource;
  137. var fragmentSource;
  138. if (baseName.vertexElement) {
  139. vertexSource = document.getElementById(baseName.vertexElement);
  140. if (!vertexSource) {
  141. vertexSource = baseName.vertexElement;
  142. }
  143. }
  144. else {
  145. vertexSource = baseName.vertex || baseName;
  146. }
  147. if (baseName.fragmentElement) {
  148. fragmentSource = document.getElementById(baseName.fragmentElement);
  149. if (!fragmentSource) {
  150. fragmentSource = baseName.fragmentElement;
  151. }
  152. }
  153. else {
  154. fragmentSource = baseName.fragment || baseName;
  155. }
  156. var finalVertexCode;
  157. this._loadVertexShaderAsync(vertexSource)
  158. .then(function (vertexCode) {
  159. return _this._processIncludesAsync(vertexCode);
  160. })
  161. .then(function (vertexCodeWithIncludes) {
  162. finalVertexCode = _this._processShaderConversion(vertexCodeWithIncludes, false);
  163. return _this._loadFragmentShaderAsync(fragmentSource);
  164. })
  165. .then(function (fragmentCode) {
  166. return _this._processIncludesAsync(fragmentCode);
  167. })
  168. .then(function (fragmentCodeWithIncludes) {
  169. var migratedFragmentCode = _this._processShaderConversion(fragmentCodeWithIncludes, true);
  170. if (baseName) {
  171. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  172. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  173. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + finalVertexCode;
  174. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  175. }
  176. else {
  177. _this._vertexSourceCode = finalVertexCode;
  178. _this._fragmentSourceCode = migratedFragmentCode;
  179. }
  180. _this._prepareEffect();
  181. });
  182. }
  183. Object.defineProperty(Effect.prototype, "key", {
  184. get: function () {
  185. return this._key;
  186. },
  187. enumerable: true,
  188. configurable: true
  189. });
  190. // Properties
  191. Effect.prototype.isReady = function () {
  192. return this._isReady;
  193. };
  194. Effect.prototype.getEngine = function () {
  195. return this._engine;
  196. };
  197. Effect.prototype.getProgram = function () {
  198. return this._program;
  199. };
  200. Effect.prototype.getAttributesNames = function () {
  201. return this._attributesNames;
  202. };
  203. Effect.prototype.getAttributeLocation = function (index) {
  204. return this._attributes[index];
  205. };
  206. Effect.prototype.getAttributeLocationByName = function (name) {
  207. var index = this._attributesNames.indexOf(name);
  208. return this._attributes[index];
  209. };
  210. Effect.prototype.getAttributesCount = function () {
  211. return this._attributes.length;
  212. };
  213. Effect.prototype.getUniformIndex = function (uniformName) {
  214. return this._uniformsNames.indexOf(uniformName);
  215. };
  216. Effect.prototype.getUniform = function (uniformName) {
  217. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  218. };
  219. Effect.prototype.getSamplers = function () {
  220. return this._samplers;
  221. };
  222. Effect.prototype.getCompilationError = function () {
  223. return this._compilationError;
  224. };
  225. // Methods
  226. Effect.prototype.executeWhenCompiled = function (func) {
  227. if (this.isReady()) {
  228. func(this);
  229. return;
  230. }
  231. this.onCompileObservable.add(function (effect) {
  232. func(effect);
  233. });
  234. };
  235. /** @ignore */
  236. Effect.prototype._loadVertexShaderAsync = function (vertex) {
  237. if (BABYLON.Tools.IsWindowObjectExist()) {
  238. // DOM element ?
  239. if (vertex instanceof HTMLElement) {
  240. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  241. return Promise.resolve(vertexCode);
  242. }
  243. }
  244. // Base64 encoded ?
  245. if (vertex.substr(0, 7) === "base64:") {
  246. var vertexBinary = window.atob(vertex.substr(7));
  247. return Promise.resolve(vertexBinary);
  248. }
  249. // Is in local store ?
  250. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  251. return Promise.resolve(Effect.ShadersStore[vertex + "VertexShader"]);
  252. }
  253. var vertexShaderUrl;
  254. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  255. vertexShaderUrl = vertex;
  256. }
  257. else {
  258. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  259. }
  260. // Vertex shader
  261. return this._engine._loadFileAsync(vertexShaderUrl + ".vertex.fx");
  262. };
  263. /** @ignore */
  264. Effect.prototype._loadFragmentShaderAsync = function (fragment) {
  265. if (BABYLON.Tools.IsWindowObjectExist()) {
  266. // DOM element ?
  267. if (fragment instanceof HTMLElement) {
  268. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  269. return Promise.resolve(fragmentCode);
  270. }
  271. }
  272. // Base64 encoded ?
  273. if (fragment.substr(0, 7) === "base64:") {
  274. var fragmentBinary = window.atob(fragment.substr(7));
  275. return Promise.resolve(fragmentBinary);
  276. }
  277. // Is in local store ?
  278. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  279. return Promise.resolve(Effect.ShadersStore[fragment + "PixelShader"]);
  280. }
  281. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  282. return Promise.resolve(Effect.ShadersStore[fragment + "FragmentShader"]);
  283. }
  284. var fragmentShaderUrl;
  285. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  286. fragmentShaderUrl = fragment;
  287. }
  288. else {
  289. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  290. }
  291. // Fragment shader
  292. return this._engine._loadFileAsync(fragmentShaderUrl + ".fragment.fx");
  293. };
  294. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  295. // Rebuild shaders source code
  296. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  297. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  298. vertexCode = prefix + vertexCode;
  299. fragmentCode = prefix + fragmentCode;
  300. // Number lines of shaders source code
  301. var i = 2;
  302. var regex = /\n/gm;
  303. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  304. i = 2;
  305. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  306. // Dump shaders name and formatted source code
  307. if (this.name.vertexElement) {
  308. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  309. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  310. }
  311. else if (this.name.vertex) {
  312. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  313. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  314. }
  315. else {
  316. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  317. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  318. }
  319. };
  320. ;
  321. Effect.prototype._processShaderConversion = function (sourceCode, isFragment) {
  322. var preparedSourceCode = this._processPrecision(sourceCode);
  323. if (this._engine.webGLVersion == 1) {
  324. return preparedSourceCode;
  325. }
  326. // Already converted
  327. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  328. return preparedSourceCode.replace("#version 300 es", "");
  329. }
  330. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  331. // Remove extensions
  332. // #extension GL_OES_standard_derivatives : enable
  333. // #extension GL_EXT_shader_texture_lod : enable
  334. // #extension GL_EXT_frag_depth : enable
  335. // #extension GL_EXT_draw_buffers : require
  336. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  337. var result = preparedSourceCode.replace(regex, "");
  338. // Migrate to GLSL v300
  339. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  340. result = result.replace(/attribute[ \t]/g, "in ");
  341. result = result.replace(/[ \t]attribute/g, " in");
  342. if (isFragment) {
  343. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  344. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  345. result = result.replace(/texture2D\s*\(/g, "texture(");
  346. result = result.replace(/textureCube\s*\(/g, "texture(");
  347. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  348. result = result.replace(/gl_FragColor/g, "glFragColor");
  349. result = result.replace(/gl_FragData/g, "glFragData");
  350. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  351. }
  352. return result;
  353. };
  354. Effect.prototype._processIncludesAsync = function (sourceCode) {
  355. var _this = this;
  356. return new Promise(function (resolve, reject) {
  357. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  358. var match = regex.exec(sourceCode);
  359. var returnValue = sourceCode;
  360. while (match != null) {
  361. var includeFile = match[1];
  362. // Uniform declaration
  363. if (includeFile.indexOf("__decl__") !== -1) {
  364. includeFile = includeFile.replace(/__decl__/, "");
  365. if (_this._engine.supportsUniformBuffers) {
  366. includeFile = includeFile.replace(/Vertex/, "Ubo");
  367. includeFile = includeFile.replace(/Fragment/, "Ubo");
  368. }
  369. includeFile = includeFile + "Declaration";
  370. }
  371. if (Effect.IncludesShadersStore[includeFile]) {
  372. // Substitution
  373. var includeContent = Effect.IncludesShadersStore[includeFile];
  374. if (match[2]) {
  375. var splits = match[3].split(",");
  376. for (var index = 0; index < splits.length; index += 2) {
  377. var source = new RegExp(splits[index], "g");
  378. var dest = splits[index + 1];
  379. includeContent = includeContent.replace(source, dest);
  380. }
  381. }
  382. if (match[4]) {
  383. var indexString = match[5];
  384. if (indexString.indexOf("..") !== -1) {
  385. var indexSplits = indexString.split("..");
  386. var minIndex = parseInt(indexSplits[0]);
  387. var maxIndex = parseInt(indexSplits[1]);
  388. var sourceIncludeContent = includeContent.slice(0);
  389. includeContent = "";
  390. if (isNaN(maxIndex)) {
  391. maxIndex = _this._indexParameters[indexSplits[1]];
  392. }
  393. for (var i = minIndex; i < maxIndex; i++) {
  394. if (!_this._engine.supportsUniformBuffers) {
  395. // Ubo replacement
  396. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  397. return p1 + "{X}";
  398. });
  399. }
  400. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  401. }
  402. }
  403. else {
  404. if (!_this._engine.supportsUniformBuffers) {
  405. // Ubo replacement
  406. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  407. return p1 + "{X}";
  408. });
  409. }
  410. includeContent = includeContent.replace(/\{X\}/g, indexString);
  411. }
  412. }
  413. // Replace
  414. returnValue = returnValue.replace(match[0], includeContent);
  415. }
  416. else {
  417. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  418. _this._engine._loadFileAsync(includeShaderUrl)
  419. .then(function (fileContent) {
  420. Effect.IncludesShadersStore[includeFile] = fileContent;
  421. return _this._processIncludesAsync(returnValue);
  422. })
  423. .then(function (returnValue) {
  424. resolve(returnValue);
  425. });
  426. return;
  427. }
  428. match = regex.exec(sourceCode);
  429. }
  430. resolve(returnValue);
  431. });
  432. };
  433. Effect.prototype._processPrecision = function (source) {
  434. if (source.indexOf("precision highp float") === -1) {
  435. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  436. source = "precision mediump float;\n" + source;
  437. }
  438. else {
  439. source = "precision highp float;\n" + source;
  440. }
  441. }
  442. else {
  443. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  444. source = source.replace("precision highp float", "precision mediump float");
  445. }
  446. }
  447. return source;
  448. };
  449. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  450. var _this = this;
  451. this._isReady = false;
  452. this._vertexSourceCodeOverride = vertexSourceCode;
  453. this._fragmentSourceCodeOverride = fragmentSourceCode;
  454. this.onError = function (effect, error) {
  455. if (onError) {
  456. onError(error);
  457. }
  458. };
  459. this.onCompiled = function () {
  460. var scenes = _this.getEngine().scenes;
  461. for (var i = 0; i < scenes.length; i++) {
  462. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  463. }
  464. if (onCompiled) {
  465. onCompiled(_this._program);
  466. }
  467. };
  468. this._fallbacks = null;
  469. this._prepareEffect();
  470. };
  471. Effect.prototype.getSpecificUniformLocations = function (names) {
  472. var engine = this._engine;
  473. return engine.getUniforms(this._program, names);
  474. };
  475. Effect.prototype._prepareEffect = function () {
  476. var attributesNames = this._attributesNames;
  477. var defines = this.defines;
  478. var fallbacks = this._fallbacks;
  479. this._valueCache = {};
  480. var previousProgram = this._program;
  481. try {
  482. var engine = this._engine;
  483. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  484. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  485. }
  486. else {
  487. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  488. }
  489. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  490. if (engine.supportsUniformBuffers) {
  491. for (var name in this._uniformBuffersNames) {
  492. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  493. }
  494. }
  495. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  496. this._attributes = engine.getAttributes(this._program, attributesNames);
  497. var index;
  498. for (index = 0; index < this._samplers.length; index++) {
  499. var sampler = this.getUniform(this._samplers[index]);
  500. if (sampler == null) {
  501. this._samplers.splice(index, 1);
  502. index--;
  503. }
  504. }
  505. engine.bindSamplers(this);
  506. this._compilationError = "";
  507. this._isReady = true;
  508. if (this.onCompiled) {
  509. this.onCompiled(this);
  510. }
  511. this.onCompileObservable.notifyObservers(this);
  512. this.onCompileObservable.clear();
  513. // Unbind mesh reference in fallbacks
  514. if (this._fallbacks) {
  515. this._fallbacks.unBindMesh();
  516. }
  517. if (previousProgram) {
  518. this.getEngine()._deleteProgram(previousProgram);
  519. }
  520. }
  521. catch (e) {
  522. this._compilationError = e.message;
  523. // Let's go through fallbacks then
  524. BABYLON.Tools.Error("Unable to compile effect:");
  525. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  526. return " " + uniform;
  527. }));
  528. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  529. return " " + attribute;
  530. }));
  531. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  532. BABYLON.Tools.Error("Error: " + this._compilationError);
  533. if (previousProgram) {
  534. this._program = previousProgram;
  535. this._isReady = true;
  536. if (this.onError) {
  537. this.onError(this, this._compilationError);
  538. }
  539. this.onErrorObservable.notifyObservers(this);
  540. }
  541. if (fallbacks && fallbacks.isMoreFallbacks) {
  542. BABYLON.Tools.Error("Trying next fallback.");
  543. this.defines = fallbacks.reduce(this.defines);
  544. this._prepareEffect();
  545. }
  546. else {
  547. if (this.onError) {
  548. this.onError(this, this._compilationError);
  549. }
  550. this.onErrorObservable.notifyObservers(this);
  551. this.onErrorObservable.clear();
  552. // Unbind mesh reference in fallbacks
  553. if (this._fallbacks) {
  554. this._fallbacks.unBindMesh();
  555. }
  556. }
  557. }
  558. };
  559. Object.defineProperty(Effect.prototype, "isSupported", {
  560. get: function () {
  561. return this._compilationError === "";
  562. },
  563. enumerable: true,
  564. configurable: true
  565. });
  566. Effect.prototype._bindTexture = function (channel, texture) {
  567. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  568. };
  569. Effect.prototype.setTexture = function (channel, texture) {
  570. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  571. };
  572. Effect.prototype.setTextureArray = function (channel, textures) {
  573. if (this._samplers.indexOf(channel + "Ex") === -1) {
  574. var initialPos = this._samplers.indexOf(channel);
  575. for (var index = 1; index < textures.length; index++) {
  576. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  577. }
  578. }
  579. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  580. };
  581. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  582. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  583. };
  584. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  585. var cache = this._valueCache[uniformName];
  586. var flag = matrix.updateFlag;
  587. if (cache !== undefined && cache === flag) {
  588. return false;
  589. }
  590. this._valueCache[uniformName] = flag;
  591. return true;
  592. };
  593. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  594. var cache = this._valueCache[uniformName];
  595. if (!cache) {
  596. cache = [x, y];
  597. this._valueCache[uniformName] = cache;
  598. return true;
  599. }
  600. var changed = false;
  601. if (cache[0] !== x) {
  602. cache[0] = x;
  603. changed = true;
  604. }
  605. if (cache[1] !== y) {
  606. cache[1] = y;
  607. changed = true;
  608. }
  609. return changed;
  610. };
  611. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  612. var cache = this._valueCache[uniformName];
  613. if (!cache) {
  614. cache = [x, y, z];
  615. this._valueCache[uniformName] = cache;
  616. return true;
  617. }
  618. var changed = false;
  619. if (cache[0] !== x) {
  620. cache[0] = x;
  621. changed = true;
  622. }
  623. if (cache[1] !== y) {
  624. cache[1] = y;
  625. changed = true;
  626. }
  627. if (cache[2] !== z) {
  628. cache[2] = z;
  629. changed = true;
  630. }
  631. return changed;
  632. };
  633. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  634. var cache = this._valueCache[uniformName];
  635. if (!cache) {
  636. cache = [x, y, z, w];
  637. this._valueCache[uniformName] = cache;
  638. return true;
  639. }
  640. var changed = false;
  641. if (cache[0] !== x) {
  642. cache[0] = x;
  643. changed = true;
  644. }
  645. if (cache[1] !== y) {
  646. cache[1] = y;
  647. changed = true;
  648. }
  649. if (cache[2] !== z) {
  650. cache[2] = z;
  651. changed = true;
  652. }
  653. if (cache[3] !== w) {
  654. cache[3] = w;
  655. changed = true;
  656. }
  657. return changed;
  658. };
  659. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  660. var bufferName = this._uniformBuffersNames[name];
  661. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  662. return;
  663. }
  664. Effect._baseCache[bufferName] = buffer;
  665. this._engine.bindUniformBufferBase(buffer, bufferName);
  666. };
  667. Effect.prototype.bindUniformBlock = function (blockName, index) {
  668. this._engine.bindUniformBlock(this._program, blockName, index);
  669. };
  670. Effect.prototype.setInt = function (uniformName, value) {
  671. var cache = this._valueCache[uniformName];
  672. if (cache !== undefined && cache === value)
  673. return this;
  674. this._valueCache[uniformName] = value;
  675. this._engine.setInt(this.getUniform(uniformName), value);
  676. return this;
  677. };
  678. Effect.prototype.setIntArray = function (uniformName, array) {
  679. this._valueCache[uniformName] = null;
  680. this._engine.setIntArray(this.getUniform(uniformName), array);
  681. return this;
  682. };
  683. Effect.prototype.setIntArray2 = function (uniformName, array) {
  684. this._valueCache[uniformName] = null;
  685. this._engine.setIntArray2(this.getUniform(uniformName), array);
  686. return this;
  687. };
  688. Effect.prototype.setIntArray3 = function (uniformName, array) {
  689. this._valueCache[uniformName] = null;
  690. this._engine.setIntArray3(this.getUniform(uniformName), array);
  691. return this;
  692. };
  693. Effect.prototype.setIntArray4 = function (uniformName, array) {
  694. this._valueCache[uniformName] = null;
  695. this._engine.setIntArray4(this.getUniform(uniformName), array);
  696. return this;
  697. };
  698. Effect.prototype.setFloatArray = function (uniformName, array) {
  699. this._valueCache[uniformName] = null;
  700. this._engine.setFloatArray(this.getUniform(uniformName), array);
  701. return this;
  702. };
  703. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  704. this._valueCache[uniformName] = null;
  705. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  706. return this;
  707. };
  708. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  709. this._valueCache[uniformName] = null;
  710. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  711. return this;
  712. };
  713. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  714. this._valueCache[uniformName] = null;
  715. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  716. return this;
  717. };
  718. Effect.prototype.setArray = function (uniformName, array) {
  719. this._valueCache[uniformName] = null;
  720. this._engine.setArray(this.getUniform(uniformName), array);
  721. return this;
  722. };
  723. Effect.prototype.setArray2 = function (uniformName, array) {
  724. this._valueCache[uniformName] = null;
  725. this._engine.setArray2(this.getUniform(uniformName), array);
  726. return this;
  727. };
  728. Effect.prototype.setArray3 = function (uniformName, array) {
  729. this._valueCache[uniformName] = null;
  730. this._engine.setArray3(this.getUniform(uniformName), array);
  731. return this;
  732. };
  733. Effect.prototype.setArray4 = function (uniformName, array) {
  734. this._valueCache[uniformName] = null;
  735. this._engine.setArray4(this.getUniform(uniformName), array);
  736. return this;
  737. };
  738. Effect.prototype.setMatrices = function (uniformName, matrices) {
  739. if (!matrices) {
  740. return this;
  741. }
  742. this._valueCache[uniformName] = null;
  743. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  744. return this;
  745. };
  746. Effect.prototype.setMatrix = function (uniformName, matrix) {
  747. if (this._cacheMatrix(uniformName, matrix)) {
  748. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  749. }
  750. return this;
  751. };
  752. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  753. this._valueCache[uniformName] = null;
  754. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  755. return this;
  756. };
  757. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  758. this._valueCache[uniformName] = null;
  759. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  760. return this;
  761. };
  762. Effect.prototype.setFloat = function (uniformName, value) {
  763. var cache = this._valueCache[uniformName];
  764. if (cache !== undefined && cache === value)
  765. return this;
  766. this._valueCache[uniformName] = value;
  767. this._engine.setFloat(this.getUniform(uniformName), value);
  768. return this;
  769. };
  770. Effect.prototype.setBool = function (uniformName, bool) {
  771. var cache = this._valueCache[uniformName];
  772. if (cache !== undefined && cache === bool)
  773. return this;
  774. this._valueCache[uniformName] = bool;
  775. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  776. return this;
  777. };
  778. Effect.prototype.setVector2 = function (uniformName, vector2) {
  779. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  780. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  781. }
  782. return this;
  783. };
  784. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  785. if (this._cacheFloat2(uniformName, x, y)) {
  786. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  787. }
  788. return this;
  789. };
  790. Effect.prototype.setVector3 = function (uniformName, vector3) {
  791. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  792. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  793. }
  794. return this;
  795. };
  796. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  797. if (this._cacheFloat3(uniformName, x, y, z)) {
  798. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  799. }
  800. return this;
  801. };
  802. Effect.prototype.setVector4 = function (uniformName, vector4) {
  803. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  804. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  805. }
  806. return this;
  807. };
  808. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  809. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  810. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  811. }
  812. return this;
  813. };
  814. Effect.prototype.setColor3 = function (uniformName, color3) {
  815. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  816. this._engine.setColor3(this.getUniform(uniformName), color3);
  817. }
  818. return this;
  819. };
  820. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  821. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  822. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  823. }
  824. return this;
  825. };
  826. Effect.ResetCache = function () {
  827. Effect._baseCache = {};
  828. };
  829. Effect._uniqueIdSeed = 0;
  830. Effect._baseCache = {};
  831. // Statics
  832. Effect.ShadersStore = {};
  833. Effect.IncludesShadersStore = {};
  834. return Effect;
  835. }());
  836. BABYLON.Effect = Effect;
  837. })(BABYLON || (BABYLON = {}));
  838. //# sourceMappingURL=babylon.effect.js.map
  839. //# sourceMappingURL=babylon.types.js.map
  840. var BABYLON;
  841. (function (BABYLON) {
  842. var KeyboardEventTypes = /** @class */ (function () {
  843. function KeyboardEventTypes() {
  844. }
  845. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  846. get: function () {
  847. return KeyboardEventTypes._KEYDOWN;
  848. },
  849. enumerable: true,
  850. configurable: true
  851. });
  852. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  853. get: function () {
  854. return KeyboardEventTypes._KEYUP;
  855. },
  856. enumerable: true,
  857. configurable: true
  858. });
  859. KeyboardEventTypes._KEYDOWN = 0x01;
  860. KeyboardEventTypes._KEYUP = 0x02;
  861. return KeyboardEventTypes;
  862. }());
  863. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  864. var KeyboardInfo = /** @class */ (function () {
  865. function KeyboardInfo(type, event) {
  866. this.type = type;
  867. this.event = event;
  868. }
  869. return KeyboardInfo;
  870. }());
  871. BABYLON.KeyboardInfo = KeyboardInfo;
  872. /**
  873. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  874. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  875. */
  876. var KeyboardInfoPre = /** @class */ (function (_super) {
  877. __extends(KeyboardInfoPre, _super);
  878. function KeyboardInfoPre(type, event) {
  879. var _this = _super.call(this, type, event) || this;
  880. _this.skipOnPointerObservable = false;
  881. return _this;
  882. }
  883. return KeyboardInfoPre;
  884. }(KeyboardInfo));
  885. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  886. })(BABYLON || (BABYLON = {}));
  887. //# sourceMappingURL=babylon.keyboardEvents.js.map
  888. var BABYLON;
  889. (function (BABYLON) {
  890. var PointerEventTypes = /** @class */ (function () {
  891. function PointerEventTypes() {
  892. }
  893. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  894. get: function () {
  895. return PointerEventTypes._POINTERDOWN;
  896. },
  897. enumerable: true,
  898. configurable: true
  899. });
  900. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  901. get: function () {
  902. return PointerEventTypes._POINTERUP;
  903. },
  904. enumerable: true,
  905. configurable: true
  906. });
  907. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  908. get: function () {
  909. return PointerEventTypes._POINTERMOVE;
  910. },
  911. enumerable: true,
  912. configurable: true
  913. });
  914. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  915. get: function () {
  916. return PointerEventTypes._POINTERWHEEL;
  917. },
  918. enumerable: true,
  919. configurable: true
  920. });
  921. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  922. get: function () {
  923. return PointerEventTypes._POINTERPICK;
  924. },
  925. enumerable: true,
  926. configurable: true
  927. });
  928. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  929. get: function () {
  930. return PointerEventTypes._POINTERTAP;
  931. },
  932. enumerable: true,
  933. configurable: true
  934. });
  935. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  936. get: function () {
  937. return PointerEventTypes._POINTERDOUBLETAP;
  938. },
  939. enumerable: true,
  940. configurable: true
  941. });
  942. PointerEventTypes._POINTERDOWN = 0x01;
  943. PointerEventTypes._POINTERUP = 0x02;
  944. PointerEventTypes._POINTERMOVE = 0x04;
  945. PointerEventTypes._POINTERWHEEL = 0x08;
  946. PointerEventTypes._POINTERPICK = 0x10;
  947. PointerEventTypes._POINTERTAP = 0x20;
  948. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  949. return PointerEventTypes;
  950. }());
  951. BABYLON.PointerEventTypes = PointerEventTypes;
  952. var PointerInfoBase = /** @class */ (function () {
  953. function PointerInfoBase(type, event) {
  954. this.type = type;
  955. this.event = event;
  956. }
  957. return PointerInfoBase;
  958. }());
  959. BABYLON.PointerInfoBase = PointerInfoBase;
  960. /**
  961. * This class is used to store pointer related info for the onPrePointerObservable event.
  962. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  963. */
  964. var PointerInfoPre = /** @class */ (function (_super) {
  965. __extends(PointerInfoPre, _super);
  966. function PointerInfoPre(type, event, localX, localY) {
  967. var _this = _super.call(this, type, event) || this;
  968. _this.skipOnPointerObservable = false;
  969. _this.localPosition = new BABYLON.Vector2(localX, localY);
  970. return _this;
  971. }
  972. return PointerInfoPre;
  973. }(PointerInfoBase));
  974. BABYLON.PointerInfoPre = PointerInfoPre;
  975. /**
  976. * This type contains all the data related to a pointer event in Babylon.js.
  977. * 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.
  978. */
  979. var PointerInfo = /** @class */ (function (_super) {
  980. __extends(PointerInfo, _super);
  981. function PointerInfo(type, event, pickInfo) {
  982. var _this = _super.call(this, type, event) || this;
  983. _this.pickInfo = pickInfo;
  984. return _this;
  985. }
  986. return PointerInfo;
  987. }(PointerInfoBase));
  988. BABYLON.PointerInfo = PointerInfo;
  989. })(BABYLON || (BABYLON = {}));
  990. //# sourceMappingURL=babylon.pointerEvents.js.map
  991. var BABYLON;
  992. (function (BABYLON) {
  993. BABYLON.ToGammaSpace = 1 / 2.2;
  994. BABYLON.ToLinearSpace = 2.2;
  995. BABYLON.Epsilon = 0.001;
  996. /**
  997. * Class used to hold a RBG color
  998. */
  999. var Color3 = /** @class */ (function () {
  1000. /**
  1001. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1002. * @param r defines the red component (between 0 and 1, default is 0)
  1003. * @param g defines the green component (between 0 and 1, default is 0)
  1004. * @param b defines the blue component (between 0 and 1, default is 0)
  1005. */
  1006. function Color3(
  1007. /**
  1008. * Defines the red component (between 0 and 1, default is 0)
  1009. */
  1010. r,
  1011. /**
  1012. * Defines the green component (between 0 and 1, default is 0)
  1013. */
  1014. g,
  1015. /**
  1016. * Defines the blue component (between 0 and 1, default is 0)
  1017. */
  1018. b) {
  1019. if (r === void 0) { r = 0; }
  1020. if (g === void 0) { g = 0; }
  1021. if (b === void 0) { b = 0; }
  1022. this.r = r;
  1023. this.g = g;
  1024. this.b = b;
  1025. }
  1026. /**
  1027. * Creates a string with the Color3 current values
  1028. * @returns the string representation of the Color3 object
  1029. */
  1030. Color3.prototype.toString = function () {
  1031. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1032. };
  1033. /**
  1034. * Returns the string "Color3"
  1035. * @returns "Color3"
  1036. */
  1037. Color3.prototype.getClassName = function () {
  1038. return "Color3";
  1039. };
  1040. /**
  1041. * Compute the Color3 hash code
  1042. * @returns an unique number that can be used to hash Color3 objects
  1043. */
  1044. Color3.prototype.getHashCode = function () {
  1045. var hash = this.r || 0;
  1046. hash = (hash * 397) ^ (this.g || 0);
  1047. hash = (hash * 397) ^ (this.b || 0);
  1048. return hash;
  1049. };
  1050. // Operators
  1051. /**
  1052. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1053. * @param array defines the array where to store the r,g,b components
  1054. * @param index defines an optional index in the target array to define where to start storing values
  1055. * @returns the current Color3 object
  1056. */
  1057. Color3.prototype.toArray = function (array, index) {
  1058. if (index === undefined) {
  1059. index = 0;
  1060. }
  1061. array[index] = this.r;
  1062. array[index + 1] = this.g;
  1063. array[index + 2] = this.b;
  1064. return this;
  1065. };
  1066. /**
  1067. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1068. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1069. * @returns a new {BABYLON.Color4} object
  1070. */
  1071. Color3.prototype.toColor4 = function (alpha) {
  1072. if (alpha === void 0) { alpha = 1; }
  1073. return new Color4(this.r, this.g, this.b, alpha);
  1074. };
  1075. /**
  1076. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1077. * @returns the new array
  1078. */
  1079. Color3.prototype.asArray = function () {
  1080. var result = new Array();
  1081. this.toArray(result, 0);
  1082. return result;
  1083. };
  1084. /**
  1085. * Returns the luminance value
  1086. * @returns a float value
  1087. */
  1088. Color3.prototype.toLuminance = function () {
  1089. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1090. };
  1091. /**
  1092. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1093. * @param otherColor defines the second operand
  1094. * @returns the new Color3 object
  1095. */
  1096. Color3.prototype.multiply = function (otherColor) {
  1097. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1098. };
  1099. /**
  1100. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1101. * @param otherColor defines the second operand
  1102. * @param result defines the Color3 object where to store the result
  1103. * @returns the current Color3
  1104. */
  1105. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1106. result.r = this.r * otherColor.r;
  1107. result.g = this.g * otherColor.g;
  1108. result.b = this.b * otherColor.b;
  1109. return this;
  1110. };
  1111. /**
  1112. * Determines equality between Color3 objects
  1113. * @param otherColor defines the second operand
  1114. * @returns true if the rgb values are equal to the passed ones
  1115. */
  1116. Color3.prototype.equals = function (otherColor) {
  1117. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1118. };
  1119. /**
  1120. * Determines equality between the current Color3 object and a set of r,b,g values
  1121. * @param r defines the red component to check
  1122. * @param g defines the green component to check
  1123. * @param b defines the blue component to check
  1124. * @returns true if the rgb values are equal to the passed ones
  1125. */
  1126. Color3.prototype.equalsFloats = function (r, g, b) {
  1127. return this.r === r && this.g === g && this.b === b;
  1128. };
  1129. /**
  1130. * Multiplies in place each rgb value by scale
  1131. * @param scale defines the scaling factor
  1132. * @returns the updated Color3.
  1133. */
  1134. Color3.prototype.scale = function (scale) {
  1135. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1136. };
  1137. /**
  1138. * Multiplies the rgb values by scale and stores the result into "result"
  1139. * @param scale defines the scaling factor
  1140. * @param result defines the Color3 object where to store the result
  1141. * @returns the unmodified current Color3.
  1142. */
  1143. Color3.prototype.scaleToRef = function (scale, result) {
  1144. result.r = this.r * scale;
  1145. result.g = this.g * scale;
  1146. result.b = this.b * scale;
  1147. return this;
  1148. };
  1149. /**
  1150. * Clamps the rgb values by the min and max values and stores the result into "result"
  1151. * @param min defines minimum clamping value (default is 0)
  1152. * @param max defines maximum clamping value (default is 1)
  1153. * @param result defines color to store the result into
  1154. * @returns the original Color3
  1155. */
  1156. Color3.prototype.clampToRef = function (min, max, result) {
  1157. if (min === void 0) { min = 0; }
  1158. if (max === void 0) { max = 1; }
  1159. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1160. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1161. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1162. return this;
  1163. };
  1164. /**
  1165. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1166. * @param otherColor defines the second operand
  1167. * @returns the new Color3
  1168. */
  1169. Color3.prototype.add = function (otherColor) {
  1170. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1171. };
  1172. /**
  1173. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1174. * @param otherColor defines the second operand
  1175. * @param result defines Color3 object to store the result into
  1176. * @returns the unmodified current Color3
  1177. */
  1178. Color3.prototype.addToRef = function (otherColor, result) {
  1179. result.r = this.r + otherColor.r;
  1180. result.g = this.g + otherColor.g;
  1181. result.b = this.b + otherColor.b;
  1182. return this;
  1183. };
  1184. /**
  1185. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1186. * @param otherColor defines the second operand
  1187. * @returns the new Color3
  1188. */
  1189. Color3.prototype.subtract = function (otherColor) {
  1190. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1191. };
  1192. /**
  1193. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1194. * @param otherColor defines the second operand
  1195. * @param result defines Color3 object to store the result into
  1196. * @returns the unmodified current Color3
  1197. */
  1198. Color3.prototype.subtractToRef = function (otherColor, result) {
  1199. result.r = this.r - otherColor.r;
  1200. result.g = this.g - otherColor.g;
  1201. result.b = this.b - otherColor.b;
  1202. return this;
  1203. };
  1204. /**
  1205. * Copy the current object
  1206. * @returns a new Color3 copied the current one
  1207. */
  1208. Color3.prototype.clone = function () {
  1209. return new Color3(this.r, this.g, this.b);
  1210. };
  1211. /**
  1212. * Copies the rgb values from the source in the current Color3
  1213. * @param source defines the source Color3 object
  1214. * @returns the updated Color3 object
  1215. */
  1216. Color3.prototype.copyFrom = function (source) {
  1217. this.r = source.r;
  1218. this.g = source.g;
  1219. this.b = source.b;
  1220. return this;
  1221. };
  1222. /**
  1223. * Updates the Color3 rgb values from the passed floats
  1224. * @param r defines the red component to read from
  1225. * @param g defines the green component to read from
  1226. * @param b defines the blue component to read from
  1227. * @returns the current Color3 object
  1228. */
  1229. Color3.prototype.copyFromFloats = function (r, g, b) {
  1230. this.r = r;
  1231. this.g = g;
  1232. this.b = b;
  1233. return this;
  1234. };
  1235. /**
  1236. * Updates the Color3 rgb values from the passed floats
  1237. * @param r defines the red component to read from
  1238. * @param g defines the green component to read from
  1239. * @param b defines the blue component to read from
  1240. * @returns the current Color3 object
  1241. */
  1242. Color3.prototype.set = function (r, g, b) {
  1243. return this.copyFromFloats(r, g, b);
  1244. };
  1245. /**
  1246. * Compute the Color3 hexadecimal code as a string
  1247. * @returns a string containing the hexadecimal representation of the Color3 object
  1248. */
  1249. Color3.prototype.toHexString = function () {
  1250. var intR = (this.r * 255) | 0;
  1251. var intG = (this.g * 255) | 0;
  1252. var intB = (this.b * 255) | 0;
  1253. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1254. };
  1255. /**
  1256. * Computes a new Color3 converted from the current one to linear space
  1257. * @returns a new Color3 object
  1258. */
  1259. Color3.prototype.toLinearSpace = function () {
  1260. var convertedColor = new Color3();
  1261. this.toLinearSpaceToRef(convertedColor);
  1262. return convertedColor;
  1263. };
  1264. /**
  1265. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1266. * @param convertedColor defines the Color3 object where to store the linear space version
  1267. * @returns the unmodified Color3
  1268. */
  1269. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1270. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1271. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1272. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1273. return this;
  1274. };
  1275. /**
  1276. * Computes a new Color3 converted from the current one to gamma space
  1277. * @returns a new Color3 object
  1278. */
  1279. Color3.prototype.toGammaSpace = function () {
  1280. var convertedColor = new Color3();
  1281. this.toGammaSpaceToRef(convertedColor);
  1282. return convertedColor;
  1283. };
  1284. /**
  1285. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1286. * @param convertedColor defines the Color3 object where to store the gamma space version
  1287. * @returns the unmodified Color3
  1288. */
  1289. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1290. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1291. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1292. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1293. return this;
  1294. };
  1295. // Statics
  1296. /**
  1297. * Creates a new Color3 from the string containing valid hexadecimal values
  1298. * @param hex defines a string containing valid hexadecimal values
  1299. * @returns a new Color3 object
  1300. */
  1301. Color3.FromHexString = function (hex) {
  1302. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1303. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  1304. return new Color3(0, 0, 0);
  1305. }
  1306. var r = parseInt(hex.substring(1, 3), 16);
  1307. var g = parseInt(hex.substring(3, 5), 16);
  1308. var b = parseInt(hex.substring(5, 7), 16);
  1309. return Color3.FromInts(r, g, b);
  1310. };
  1311. /**
  1312. * Creates a new Vector3 from the starting index of the passed array
  1313. * @param array defines the source array
  1314. * @param offset defines an offset in the source array
  1315. * @returns a new Color3 object
  1316. */
  1317. Color3.FromArray = function (array, offset) {
  1318. if (offset === void 0) { offset = 0; }
  1319. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1320. };
  1321. /**
  1322. * Creates a new Color3 from integer values (< 256)
  1323. * @param r defines the red component to read from (value between 0 and 255)
  1324. * @param g defines the green component to read from (value between 0 and 255)
  1325. * @param b defines the blue component to read from (value between 0 and 255)
  1326. * @returns a new Color3 object
  1327. */
  1328. Color3.FromInts = function (r, g, b) {
  1329. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1330. };
  1331. /**
  1332. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1333. * @param start defines the start Color3 value
  1334. * @param end defines the end Color3 value
  1335. * @param amount defines the gradient value between start and end
  1336. * @returns a new Color3 object
  1337. */
  1338. Color3.Lerp = function (start, end, amount) {
  1339. var r = start.r + ((end.r - start.r) * amount);
  1340. var g = start.g + ((end.g - start.g) * amount);
  1341. var b = start.b + ((end.b - start.b) * amount);
  1342. return new Color3(r, g, b);
  1343. };
  1344. /**
  1345. * Returns a Color3 value containing a red color
  1346. * @returns a new Color3 object
  1347. */
  1348. Color3.Red = function () { return new Color3(1, 0, 0); };
  1349. /**
  1350. * Returns a Color3 value containing a green color
  1351. * @returns a new Color3 object
  1352. */
  1353. Color3.Green = function () { return new Color3(0, 1, 0); };
  1354. /**
  1355. * Returns a Color3 value containing a blue color
  1356. * @returns a new Color3 object
  1357. */
  1358. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1359. /**
  1360. * Returns a Color3 value containing a black color
  1361. * @returns a new Color3 object
  1362. */
  1363. Color3.Black = function () { return new Color3(0, 0, 0); };
  1364. /**
  1365. * Returns a Color3 value containing a white color
  1366. * @returns a new Color3 object
  1367. */
  1368. Color3.White = function () { return new Color3(1, 1, 1); };
  1369. /**
  1370. * Returns a Color3 value containing a purple color
  1371. * @returns a new Color3 object
  1372. */
  1373. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1374. /**
  1375. * Returns a Color3 value containing a magenta color
  1376. * @returns a new Color3 object
  1377. */
  1378. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1379. /**
  1380. * Returns a Color3 value containing a yellow color
  1381. * @returns a new Color3 object
  1382. */
  1383. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1384. /**
  1385. * Returns a Color3 value containing a gray color
  1386. * @returns a new Color3 object
  1387. */
  1388. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1389. /**
  1390. * Returns a Color3 value containing a teal color
  1391. * @returns a new Color3 object
  1392. */
  1393. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1394. /**
  1395. * Returns a Color3 value containing a random color
  1396. * @returns a new Color3 object
  1397. */
  1398. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1399. return Color3;
  1400. }());
  1401. BABYLON.Color3 = Color3;
  1402. /**
  1403. * Class used to hold a RBGA color
  1404. */
  1405. var Color4 = /** @class */ (function () {
  1406. /**
  1407. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1408. * @param r defines the red component (between 0 and 1, default is 0)
  1409. * @param g defines the green component (between 0 and 1, default is 0)
  1410. * @param b defines the blue component (between 0 and 1, default is 0)
  1411. * @param a defines the alpha component (between 0 and 1, default is 1)
  1412. */
  1413. function Color4(
  1414. /**
  1415. * Defines the red component (between 0 and 1, default is 0)
  1416. */
  1417. r,
  1418. /**
  1419. * Defines the green component (between 0 and 1, default is 0)
  1420. */
  1421. g,
  1422. /**
  1423. * Defines the blue component (between 0 and 1, default is 0)
  1424. */
  1425. b,
  1426. /**
  1427. * Defines the alpha component (between 0 and 1, default is 1)
  1428. */
  1429. a) {
  1430. if (r === void 0) { r = 0; }
  1431. if (g === void 0) { g = 0; }
  1432. if (b === void 0) { b = 0; }
  1433. if (a === void 0) { a = 1; }
  1434. this.r = r;
  1435. this.g = g;
  1436. this.b = b;
  1437. this.a = a;
  1438. }
  1439. // Operators
  1440. /**
  1441. * Adds in place the passed Color4 values to the current Color4 object
  1442. * @param right defines the second operand
  1443. * @returns the current updated Color4 object
  1444. */
  1445. Color4.prototype.addInPlace = function (right) {
  1446. this.r += right.r;
  1447. this.g += right.g;
  1448. this.b += right.b;
  1449. this.a += right.a;
  1450. return this;
  1451. };
  1452. /**
  1453. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1454. * @returns the new array
  1455. */
  1456. Color4.prototype.asArray = function () {
  1457. var result = new Array();
  1458. this.toArray(result, 0);
  1459. return result;
  1460. };
  1461. /**
  1462. * Stores from the starting index in the passed array the Color4 successive values
  1463. * @param array defines the array where to store the r,g,b components
  1464. * @param index defines an optional index in the target array to define where to start storing values
  1465. * @returns the current Color4 object
  1466. */
  1467. Color4.prototype.toArray = function (array, index) {
  1468. if (index === undefined) {
  1469. index = 0;
  1470. }
  1471. array[index] = this.r;
  1472. array[index + 1] = this.g;
  1473. array[index + 2] = this.b;
  1474. array[index + 3] = this.a;
  1475. return this;
  1476. };
  1477. /**
  1478. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  1479. * @param right defines the second operand
  1480. * @returns a new Color4 object
  1481. */
  1482. Color4.prototype.add = function (right) {
  1483. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1484. };
  1485. /**
  1486. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  1487. * @param right defines the second operand
  1488. * @returns a new Color4 object
  1489. */
  1490. Color4.prototype.subtract = function (right) {
  1491. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1492. };
  1493. /**
  1494. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  1495. * @param right defines the second operand
  1496. * @param result defines the Color4 object where to store the result
  1497. * @returns the current Color4 object
  1498. */
  1499. Color4.prototype.subtractToRef = function (right, result) {
  1500. result.r = this.r - right.r;
  1501. result.g = this.g - right.g;
  1502. result.b = this.b - right.b;
  1503. result.a = this.a - right.a;
  1504. return this;
  1505. };
  1506. /**
  1507. * Creates a new Color4 with the current Color4 values multiplied by scale
  1508. * @param scale defines the scaling factor to apply
  1509. * @returns a new Color4 object
  1510. */
  1511. Color4.prototype.scale = function (scale) {
  1512. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1513. };
  1514. /**
  1515. * Multiplies the current Color4 values by scale and stores the result in "result"
  1516. * @param scale defines the scaling factor to apply
  1517. * @param result defines the Color4 object where to store the result
  1518. * @returns the current Color4.
  1519. */
  1520. Color4.prototype.scaleToRef = function (scale, result) {
  1521. result.r = this.r * scale;
  1522. result.g = this.g * scale;
  1523. result.b = this.b * scale;
  1524. result.a = this.a * scale;
  1525. return this;
  1526. };
  1527. /**
  1528. * Clamps the rgb values by the min and max values and stores the result into "result"
  1529. * @param min defines minimum clamping value (default is 0)
  1530. * @param max defines maximum clamping value (default is 1)
  1531. * @param result defines color to store the result into.
  1532. * @returns the cuurent Color4
  1533. */
  1534. Color4.prototype.clampToRef = function (min, max, result) {
  1535. if (min === void 0) { min = 0; }
  1536. if (max === void 0) { max = 1; }
  1537. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1538. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1539. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1540. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1541. return this;
  1542. };
  1543. /**
  1544. * Multipy an Color4 value by another and return a new Color4 object
  1545. * @param color defines the Color4 value to multiply by
  1546. * @returns a new Color4 object
  1547. */
  1548. Color4.prototype.multiply = function (color) {
  1549. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1550. };
  1551. /**
  1552. * Multipy a Color4 value by another and push the result in a reference value
  1553. * @param color defines the Color4 value to multiply by
  1554. * @param result defines the Color4 to fill the result in
  1555. * @returns the result Color4
  1556. */
  1557. Color4.prototype.multiplyToRef = function (color, result) {
  1558. result.r = this.r * color.r;
  1559. result.g = this.g * color.g;
  1560. result.b = this.b * color.b;
  1561. result.a = this.a * color.a;
  1562. return result;
  1563. };
  1564. /**
  1565. * Creates a string with the Color4 current values
  1566. * @returns the string representation of the Color4 object
  1567. */
  1568. Color4.prototype.toString = function () {
  1569. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1570. };
  1571. /**
  1572. * Returns the string "Color4"
  1573. * @returns "Color4"
  1574. */
  1575. Color4.prototype.getClassName = function () {
  1576. return "Color4";
  1577. };
  1578. /**
  1579. * Compute the Color4 hash code
  1580. * @returns an unique number that can be used to hash Color4 objects
  1581. */
  1582. Color4.prototype.getHashCode = function () {
  1583. var hash = this.r || 0;
  1584. hash = (hash * 397) ^ (this.g || 0);
  1585. hash = (hash * 397) ^ (this.b || 0);
  1586. hash = (hash * 397) ^ (this.a || 0);
  1587. return hash;
  1588. };
  1589. /**
  1590. * Creates a new Color4 copied from the current one
  1591. * @returns a new Color4 object
  1592. */
  1593. Color4.prototype.clone = function () {
  1594. return new Color4(this.r, this.g, this.b, this.a);
  1595. };
  1596. /**
  1597. * Copies the passed Color4 values into the current one
  1598. * @param source defines the source Color4 object
  1599. * @returns the current updated Color4 object
  1600. */
  1601. Color4.prototype.copyFrom = function (source) {
  1602. this.r = source.r;
  1603. this.g = source.g;
  1604. this.b = source.b;
  1605. this.a = source.a;
  1606. return this;
  1607. };
  1608. /**
  1609. * Copies the passed float values into the current one
  1610. * @param r defines the red component to read from
  1611. * @param g defines the green component to read from
  1612. * @param b defines the blue component to read from
  1613. * @param a defines the alpha component to read from
  1614. * @returns the current updated Color4 object
  1615. */
  1616. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  1617. this.r = r;
  1618. this.g = g;
  1619. this.b = b;
  1620. this.a = a;
  1621. return this;
  1622. };
  1623. /**
  1624. * Copies the passed float values into the current one
  1625. * @param r defines the red component to read from
  1626. * @param g defines the green component to read from
  1627. * @param b defines the blue component to read from
  1628. * @param a defines the alpha component to read from
  1629. * @returns the current updated Color4 object
  1630. */
  1631. Color4.prototype.set = function (r, g, b, a) {
  1632. return this.copyFromFloats(r, g, b, a);
  1633. };
  1634. /**
  1635. * Compute the Color4 hexadecimal code as a string
  1636. * @returns a string containing the hexadecimal representation of the Color4 object
  1637. */
  1638. Color4.prototype.toHexString = function () {
  1639. var intR = (this.r * 255) | 0;
  1640. var intG = (this.g * 255) | 0;
  1641. var intB = (this.b * 255) | 0;
  1642. var intA = (this.a * 255) | 0;
  1643. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  1644. };
  1645. /**
  1646. * Computes a new Color4 converted from the current one to linear space
  1647. * @returns a new Color4 object
  1648. */
  1649. Color4.prototype.toLinearSpace = function () {
  1650. var convertedColor = new Color4();
  1651. this.toLinearSpaceToRef(convertedColor);
  1652. return convertedColor;
  1653. };
  1654. /**
  1655. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  1656. * @param convertedColor defines the Color4 object where to store the linear space version
  1657. * @returns the unmodified Color4
  1658. */
  1659. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  1660. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1661. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1662. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1663. convertedColor.a = this.a;
  1664. return this;
  1665. };
  1666. /**
  1667. * Computes a new Color4 converted from the current one to gamma space
  1668. * @returns a new Color4 object
  1669. */
  1670. Color4.prototype.toGammaSpace = function () {
  1671. var convertedColor = new Color4();
  1672. this.toGammaSpaceToRef(convertedColor);
  1673. return convertedColor;
  1674. };
  1675. /**
  1676. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  1677. * @param convertedColor defines the Color4 object where to store the gamma space version
  1678. * @returns the unmodified Color4
  1679. */
  1680. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  1681. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1682. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1683. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1684. convertedColor.a = this.a;
  1685. return this;
  1686. };
  1687. // Statics
  1688. /**
  1689. * Creates a new Color4 from the string containing valid hexadecimal values
  1690. * @param hex defines a string containing valid hexadecimal values
  1691. * @returns a new Color4 object
  1692. */
  1693. Color4.FromHexString = function (hex) {
  1694. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  1695. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  1696. return new Color4(0.0, 0.0, 0.0, 0.0);
  1697. }
  1698. var r = parseInt(hex.substring(1, 3), 16);
  1699. var g = parseInt(hex.substring(3, 5), 16);
  1700. var b = parseInt(hex.substring(5, 7), 16);
  1701. var a = parseInt(hex.substring(7, 9), 16);
  1702. return Color4.FromInts(r, g, b, a);
  1703. };
  1704. /**
  1705. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  1706. * @param left defines the start value
  1707. * @param right defines the end value
  1708. * @param amount defines the gradient factor
  1709. * @returns a new Color4 object
  1710. */
  1711. Color4.Lerp = function (left, right, amount) {
  1712. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  1713. Color4.LerpToRef(left, right, amount, result);
  1714. return result;
  1715. };
  1716. /**
  1717. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  1718. * @param left defines the start value
  1719. * @param right defines the end value
  1720. * @param amount defines the gradient factor
  1721. * @param result defines the Color4 object where to store data
  1722. */
  1723. Color4.LerpToRef = function (left, right, amount, result) {
  1724. result.r = left.r + (right.r - left.r) * amount;
  1725. result.g = left.g + (right.g - left.g) * amount;
  1726. result.b = left.b + (right.b - left.b) * amount;
  1727. result.a = left.a + (right.a - left.a) * amount;
  1728. };
  1729. /**
  1730. * Creates a new Color4 from the starting index element of the passed array
  1731. * @param array defines the source array to read from
  1732. * @param offset defines the offset in the source array
  1733. * @returns a new Color4 object
  1734. */
  1735. Color4.FromArray = function (array, offset) {
  1736. if (offset === void 0) { offset = 0; }
  1737. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1738. };
  1739. /**
  1740. * Creates a new Color3 from integer values (< 256)
  1741. * @param r defines the red component to read from (value between 0 and 255)
  1742. * @param g defines the green component to read from (value between 0 and 255)
  1743. * @param b defines the blue component to read from (value between 0 and 255)
  1744. * @param a defines the alpha component to read from (value between 0 and 255)
  1745. * @returns a new Color3 object
  1746. */
  1747. Color4.FromInts = function (r, g, b, a) {
  1748. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  1749. };
  1750. /**
  1751. * Check the content of a given array and convert it to an array containing RGBA data
  1752. * If the original array was already containing count * 4 values then it is returned directly
  1753. * @param colors defines the array to check
  1754. * @param count defines the number of RGBA data to expect
  1755. * @returns an array containing count * 4 values (RGBA)
  1756. */
  1757. Color4.CheckColors4 = function (colors, count) {
  1758. // Check if color3 was used
  1759. if (colors.length === count * 3) {
  1760. var colors4 = [];
  1761. for (var index = 0; index < colors.length; index += 3) {
  1762. var newIndex = (index / 3) * 4;
  1763. colors4[newIndex] = colors[index];
  1764. colors4[newIndex + 1] = colors[index + 1];
  1765. colors4[newIndex + 2] = colors[index + 2];
  1766. colors4[newIndex + 3] = 1.0;
  1767. }
  1768. return colors4;
  1769. }
  1770. return colors;
  1771. };
  1772. return Color4;
  1773. }());
  1774. BABYLON.Color4 = Color4;
  1775. var Vector2 = /** @class */ (function () {
  1776. /**
  1777. * Creates a new Vector2 from the passed x and y coordinates.
  1778. */
  1779. function Vector2(x, y) {
  1780. this.x = x;
  1781. this.y = y;
  1782. }
  1783. /**
  1784. * Returns a string with the Vector2 coordinates.
  1785. */
  1786. Vector2.prototype.toString = function () {
  1787. return "{X: " + this.x + " Y:" + this.y + "}";
  1788. };
  1789. /**
  1790. * Returns the string "Vector2"
  1791. */
  1792. Vector2.prototype.getClassName = function () {
  1793. return "Vector2";
  1794. };
  1795. /**
  1796. * Returns the Vector2 hash code as a number.
  1797. */
  1798. Vector2.prototype.getHashCode = function () {
  1799. var hash = this.x || 0;
  1800. hash = (hash * 397) ^ (this.y || 0);
  1801. return hash;
  1802. };
  1803. // Operators
  1804. /**
  1805. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  1806. * Returns the Vector2.
  1807. */
  1808. Vector2.prototype.toArray = function (array, index) {
  1809. if (index === void 0) { index = 0; }
  1810. array[index] = this.x;
  1811. array[index + 1] = this.y;
  1812. return this;
  1813. };
  1814. /**
  1815. * Returns a new array with 2 elements : the Vector2 coordinates.
  1816. */
  1817. Vector2.prototype.asArray = function () {
  1818. var result = new Array();
  1819. this.toArray(result, 0);
  1820. return result;
  1821. };
  1822. /**
  1823. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  1824. * Returns the updated Vector2.
  1825. */
  1826. Vector2.prototype.copyFrom = function (source) {
  1827. this.x = source.x;
  1828. this.y = source.y;
  1829. return this;
  1830. };
  1831. /**
  1832. * Sets the Vector2 coordinates with the passed floats.
  1833. * Returns the updated Vector2.
  1834. */
  1835. Vector2.prototype.copyFromFloats = function (x, y) {
  1836. this.x = x;
  1837. this.y = y;
  1838. return this;
  1839. };
  1840. /**
  1841. * Sets the Vector2 coordinates with the passed floats.
  1842. * Returns the updated Vector2.
  1843. */
  1844. Vector2.prototype.set = function (x, y) {
  1845. return this.copyFromFloats(x, y);
  1846. };
  1847. /**
  1848. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  1849. */
  1850. Vector2.prototype.add = function (otherVector) {
  1851. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  1852. };
  1853. /**
  1854. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  1855. * Returns the Vector2.
  1856. */
  1857. Vector2.prototype.addToRef = function (otherVector, result) {
  1858. result.x = this.x + otherVector.x;
  1859. result.y = this.y + otherVector.y;
  1860. return this;
  1861. };
  1862. /**
  1863. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  1864. * Returns the updated Vector2.
  1865. */
  1866. Vector2.prototype.addInPlace = function (otherVector) {
  1867. this.x += otherVector.x;
  1868. this.y += otherVector.y;
  1869. return this;
  1870. };
  1871. /**
  1872. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  1873. */
  1874. Vector2.prototype.addVector3 = function (otherVector) {
  1875. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  1876. };
  1877. /**
  1878. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  1879. */
  1880. Vector2.prototype.subtract = function (otherVector) {
  1881. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  1882. };
  1883. /**
  1884. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  1885. * Returns the Vector2.
  1886. */
  1887. Vector2.prototype.subtractToRef = function (otherVector, result) {
  1888. result.x = this.x - otherVector.x;
  1889. result.y = this.y - otherVector.y;
  1890. return this;
  1891. };
  1892. /**
  1893. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  1894. * Returns the updated Vector2.
  1895. */
  1896. Vector2.prototype.subtractInPlace = function (otherVector) {
  1897. this.x -= otherVector.x;
  1898. this.y -= otherVector.y;
  1899. return this;
  1900. };
  1901. /**
  1902. * Multiplies in place the current Vector2 coordinates by the passed ones.
  1903. * Returns the updated Vector2.
  1904. */
  1905. Vector2.prototype.multiplyInPlace = function (otherVector) {
  1906. this.x *= otherVector.x;
  1907. this.y *= otherVector.y;
  1908. return this;
  1909. };
  1910. /**
  1911. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  1912. */
  1913. Vector2.prototype.multiply = function (otherVector) {
  1914. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  1915. };
  1916. /**
  1917. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  1918. * Returns the Vector2.
  1919. */
  1920. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  1921. result.x = this.x * otherVector.x;
  1922. result.y = this.y * otherVector.y;
  1923. return this;
  1924. };
  1925. /**
  1926. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  1927. */
  1928. Vector2.prototype.multiplyByFloats = function (x, y) {
  1929. return new Vector2(this.x * x, this.y * y);
  1930. };
  1931. /**
  1932. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  1933. */
  1934. Vector2.prototype.divide = function (otherVector) {
  1935. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  1936. };
  1937. /**
  1938. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  1939. * Returns the Vector2.
  1940. */
  1941. Vector2.prototype.divideToRef = function (otherVector, result) {
  1942. result.x = this.x / otherVector.x;
  1943. result.y = this.y / otherVector.y;
  1944. return this;
  1945. };
  1946. /**
  1947. * Divides the current Vector3 coordinates by the passed ones.
  1948. * Returns the updated Vector3.
  1949. */
  1950. Vector2.prototype.divideInPlace = function (otherVector) {
  1951. return this.divideToRef(otherVector, this);
  1952. };
  1953. /**
  1954. * Returns a new Vector2 with current Vector2 negated coordinates.
  1955. */
  1956. Vector2.prototype.negate = function () {
  1957. return new Vector2(-this.x, -this.y);
  1958. };
  1959. /**
  1960. * Multiply the Vector2 coordinates by scale.
  1961. * Returns the updated Vector2.
  1962. */
  1963. Vector2.prototype.scaleInPlace = function (scale) {
  1964. this.x *= scale;
  1965. this.y *= scale;
  1966. return this;
  1967. };
  1968. /**
  1969. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  1970. */
  1971. Vector2.prototype.scale = function (scale) {
  1972. return new Vector2(this.x * scale, this.y * scale);
  1973. };
  1974. /**
  1975. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  1976. */
  1977. Vector2.prototype.equals = function (otherVector) {
  1978. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  1979. };
  1980. /**
  1981. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  1982. */
  1983. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1984. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1985. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  1986. };
  1987. // Properties
  1988. /**
  1989. * Returns the vector length (float).
  1990. */
  1991. Vector2.prototype.length = function () {
  1992. return Math.sqrt(this.x * this.x + this.y * this.y);
  1993. };
  1994. /**
  1995. * Returns the vector squared length (float);
  1996. */
  1997. Vector2.prototype.lengthSquared = function () {
  1998. return (this.x * this.x + this.y * this.y);
  1999. };
  2000. // Methods
  2001. /**
  2002. * Normalize the vector.
  2003. * Returns the updated Vector2.
  2004. */
  2005. Vector2.prototype.normalize = function () {
  2006. var len = this.length();
  2007. if (len === 0)
  2008. return this;
  2009. var num = 1.0 / len;
  2010. this.x *= num;
  2011. this.y *= num;
  2012. return this;
  2013. };
  2014. /**
  2015. * Returns a new Vector2 copied from the Vector2.
  2016. */
  2017. Vector2.prototype.clone = function () {
  2018. return new Vector2(this.x, this.y);
  2019. };
  2020. // Statics
  2021. /**
  2022. * Returns a new Vector2(0, 0)
  2023. */
  2024. Vector2.Zero = function () {
  2025. return new Vector2(0, 0);
  2026. };
  2027. /**
  2028. * Returns a new Vector2(1, 1)
  2029. */
  2030. Vector2.One = function () {
  2031. return new Vector2(1, 1);
  2032. };
  2033. /**
  2034. * Returns a new Vector2 set from the passed index element of the passed array.
  2035. */
  2036. Vector2.FromArray = function (array, offset) {
  2037. if (offset === void 0) { offset = 0; }
  2038. return new Vector2(array[offset], array[offset + 1]);
  2039. };
  2040. /**
  2041. * Sets "result" from the passed index element of the passed array.
  2042. */
  2043. Vector2.FromArrayToRef = function (array, offset, result) {
  2044. result.x = array[offset];
  2045. result.y = array[offset + 1];
  2046. };
  2047. /**
  2048. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2049. */
  2050. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2051. var squared = amount * amount;
  2052. var cubed = amount * squared;
  2053. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2054. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2055. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2056. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2057. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2058. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2059. return new Vector2(x, y);
  2060. };
  2061. /**
  2062. * 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".
  2063. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2064. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2065. */
  2066. Vector2.Clamp = function (value, min, max) {
  2067. var x = value.x;
  2068. x = (x > max.x) ? max.x : x;
  2069. x = (x < min.x) ? min.x : x;
  2070. var y = value.y;
  2071. y = (y > max.y) ? max.y : y;
  2072. y = (y < min.y) ? min.y : y;
  2073. return new Vector2(x, y);
  2074. };
  2075. /**
  2076. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2077. */
  2078. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2079. var squared = amount * amount;
  2080. var cubed = amount * squared;
  2081. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2082. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2083. var part3 = (cubed - (2.0 * squared)) + amount;
  2084. var part4 = cubed - squared;
  2085. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2086. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2087. return new Vector2(x, y);
  2088. };
  2089. /**
  2090. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2091. */
  2092. Vector2.Lerp = function (start, end, amount) {
  2093. var x = start.x + ((end.x - start.x) * amount);
  2094. var y = start.y + ((end.y - start.y) * amount);
  2095. return new Vector2(x, y);
  2096. };
  2097. /**
  2098. * Returns the dot product (float) of the vector "left" and the vector "right".
  2099. */
  2100. Vector2.Dot = function (left, right) {
  2101. return left.x * right.x + left.y * right.y;
  2102. };
  2103. /**
  2104. * Returns a new Vector2 equal to the normalized passed vector.
  2105. */
  2106. Vector2.Normalize = function (vector) {
  2107. var newVector = vector.clone();
  2108. newVector.normalize();
  2109. return newVector;
  2110. };
  2111. /**
  2112. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2113. */
  2114. Vector2.Minimize = function (left, right) {
  2115. var x = (left.x < right.x) ? left.x : right.x;
  2116. var y = (left.y < right.y) ? left.y : right.y;
  2117. return new Vector2(x, y);
  2118. };
  2119. /**
  2120. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2121. */
  2122. Vector2.Maximize = function (left, right) {
  2123. var x = (left.x > right.x) ? left.x : right.x;
  2124. var y = (left.y > right.y) ? left.y : right.y;
  2125. return new Vector2(x, y);
  2126. };
  2127. /**
  2128. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2129. */
  2130. Vector2.Transform = function (vector, transformation) {
  2131. var r = Vector2.Zero();
  2132. Vector2.TransformToRef(vector, transformation, r);
  2133. return r;
  2134. };
  2135. /**
  2136. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2137. */
  2138. Vector2.TransformToRef = function (vector, transformation, result) {
  2139. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2140. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2141. result.x = x;
  2142. result.y = y;
  2143. };
  2144. /**
  2145. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2146. */
  2147. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2148. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2149. var sign = a < 0 ? -1 : 1;
  2150. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2151. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2152. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2153. };
  2154. /**
  2155. * Returns the distance (float) between the vectors "value1" and "value2".
  2156. */
  2157. Vector2.Distance = function (value1, value2) {
  2158. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2159. };
  2160. /**
  2161. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2162. */
  2163. Vector2.DistanceSquared = function (value1, value2) {
  2164. var x = value1.x - value2.x;
  2165. var y = value1.y - value2.y;
  2166. return (x * x) + (y * y);
  2167. };
  2168. /**
  2169. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2170. */
  2171. Vector2.Center = function (value1, value2) {
  2172. var center = value1.add(value2);
  2173. center.scaleInPlace(0.5);
  2174. return center;
  2175. };
  2176. /**
  2177. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2178. */
  2179. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2180. var l2 = Vector2.DistanceSquared(segA, segB);
  2181. if (l2 === 0.0) {
  2182. return Vector2.Distance(p, segA);
  2183. }
  2184. var v = segB.subtract(segA);
  2185. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2186. var proj = segA.add(v.multiplyByFloats(t, t));
  2187. return Vector2.Distance(p, proj);
  2188. };
  2189. return Vector2;
  2190. }());
  2191. BABYLON.Vector2 = Vector2;
  2192. var Vector3 = /** @class */ (function () {
  2193. /**
  2194. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2195. * A Vector3 is the main object used in 3D geometry.
  2196. * It can represent etiher the coordinates of a point the space, either a direction.
  2197. */
  2198. function Vector3(x, y, z) {
  2199. this.x = x;
  2200. this.y = y;
  2201. this.z = z;
  2202. }
  2203. /**
  2204. * Returns a string with the Vector3 coordinates.
  2205. */
  2206. Vector3.prototype.toString = function () {
  2207. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2208. };
  2209. /**
  2210. * Returns the string "Vector3"
  2211. */
  2212. Vector3.prototype.getClassName = function () {
  2213. return "Vector3";
  2214. };
  2215. /**
  2216. * Returns the Vector hash code.
  2217. */
  2218. Vector3.prototype.getHashCode = function () {
  2219. var hash = this.x || 0;
  2220. hash = (hash * 397) ^ (this.y || 0);
  2221. hash = (hash * 397) ^ (this.z || 0);
  2222. return hash;
  2223. };
  2224. // Operators
  2225. /**
  2226. * Returns a new array with three elements : the coordinates the Vector3.
  2227. */
  2228. Vector3.prototype.asArray = function () {
  2229. var result = [];
  2230. this.toArray(result, 0);
  2231. return result;
  2232. };
  2233. /**
  2234. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  2235. * Returns the Vector3.
  2236. */
  2237. Vector3.prototype.toArray = function (array, index) {
  2238. if (index === void 0) { index = 0; }
  2239. array[index] = this.x;
  2240. array[index + 1] = this.y;
  2241. array[index + 2] = this.z;
  2242. return this;
  2243. };
  2244. /**
  2245. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  2246. */
  2247. Vector3.prototype.toQuaternion = function () {
  2248. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2249. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2250. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2251. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2252. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2253. var cosy = Math.cos(this.y * 0.5);
  2254. var siny = Math.sin(this.y * 0.5);
  2255. result.x = coszMinusx * siny;
  2256. result.y = -sinzMinusx * siny;
  2257. result.z = sinxPlusz * cosy;
  2258. result.w = cosxPlusz * cosy;
  2259. return result;
  2260. };
  2261. /**
  2262. * Adds the passed vector to the current Vector3.
  2263. * Returns the updated Vector3.
  2264. */
  2265. Vector3.prototype.addInPlace = function (otherVector) {
  2266. this.x += otherVector.x;
  2267. this.y += otherVector.y;
  2268. this.z += otherVector.z;
  2269. return this;
  2270. };
  2271. /**
  2272. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  2273. */
  2274. Vector3.prototype.add = function (otherVector) {
  2275. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2276. };
  2277. /**
  2278. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  2279. * Returns the current Vector3.
  2280. */
  2281. Vector3.prototype.addToRef = function (otherVector, result) {
  2282. result.x = this.x + otherVector.x;
  2283. result.y = this.y + otherVector.y;
  2284. result.z = this.z + otherVector.z;
  2285. return this;
  2286. };
  2287. /**
  2288. * Subtract the passed vector from the current Vector3.
  2289. * Returns the updated Vector3.
  2290. */
  2291. Vector3.prototype.subtractInPlace = function (otherVector) {
  2292. this.x -= otherVector.x;
  2293. this.y -= otherVector.y;
  2294. this.z -= otherVector.z;
  2295. return this;
  2296. };
  2297. /**
  2298. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  2299. */
  2300. Vector3.prototype.subtract = function (otherVector) {
  2301. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2302. };
  2303. /**
  2304. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2305. * Returns the current Vector3.
  2306. */
  2307. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2308. result.x = this.x - otherVector.x;
  2309. result.y = this.y - otherVector.y;
  2310. result.z = this.z - otherVector.z;
  2311. return this;
  2312. };
  2313. /**
  2314. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  2315. */
  2316. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2317. return new Vector3(this.x - x, this.y - y, this.z - z);
  2318. };
  2319. /**
  2320. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  2321. * Returns the current Vector3.
  2322. */
  2323. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2324. result.x = this.x - x;
  2325. result.y = this.y - y;
  2326. result.z = this.z - z;
  2327. return this;
  2328. };
  2329. /**
  2330. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  2331. */
  2332. Vector3.prototype.negate = function () {
  2333. return new Vector3(-this.x, -this.y, -this.z);
  2334. };
  2335. /**
  2336. * Multiplies the Vector3 coordinates by the float "scale".
  2337. * Returns the updated Vector3.
  2338. */
  2339. Vector3.prototype.scaleInPlace = function (scale) {
  2340. this.x *= scale;
  2341. this.y *= scale;
  2342. this.z *= scale;
  2343. return this;
  2344. };
  2345. /**
  2346. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  2347. */
  2348. Vector3.prototype.scale = function (scale) {
  2349. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2350. };
  2351. /**
  2352. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  2353. * Returns the current Vector3.
  2354. */
  2355. Vector3.prototype.scaleToRef = function (scale, result) {
  2356. result.x = this.x * scale;
  2357. result.y = this.y * scale;
  2358. result.z = this.z * scale;
  2359. return this;
  2360. };
  2361. /**
  2362. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  2363. */
  2364. Vector3.prototype.equals = function (otherVector) {
  2365. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2366. };
  2367. /**
  2368. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  2369. */
  2370. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2371. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2372. 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);
  2373. };
  2374. /**
  2375. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  2376. */
  2377. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2378. return this.x === x && this.y === y && this.z === z;
  2379. };
  2380. /**
  2381. * Muliplies the current Vector3 coordinates by the passed ones.
  2382. * Returns the updated Vector3.
  2383. */
  2384. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2385. this.x *= otherVector.x;
  2386. this.y *= otherVector.y;
  2387. this.z *= otherVector.z;
  2388. return this;
  2389. };
  2390. /**
  2391. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  2392. */
  2393. Vector3.prototype.multiply = function (otherVector) {
  2394. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2395. };
  2396. /**
  2397. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  2398. * Returns the current Vector3.
  2399. */
  2400. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2401. result.x = this.x * otherVector.x;
  2402. result.y = this.y * otherVector.y;
  2403. result.z = this.z * otherVector.z;
  2404. return this;
  2405. };
  2406. /**
  2407. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  2408. */
  2409. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2410. return new Vector3(this.x * x, this.y * y, this.z * z);
  2411. };
  2412. /**
  2413. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  2414. */
  2415. Vector3.prototype.divide = function (otherVector) {
  2416. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2417. };
  2418. /**
  2419. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  2420. * Returns the current Vector3.
  2421. */
  2422. Vector3.prototype.divideToRef = function (otherVector, result) {
  2423. result.x = this.x / otherVector.x;
  2424. result.y = this.y / otherVector.y;
  2425. result.z = this.z / otherVector.z;
  2426. return this;
  2427. };
  2428. /**
  2429. * Divides the current Vector3 coordinates by the passed ones.
  2430. * Returns the updated Vector3.
  2431. */
  2432. Vector3.prototype.divideInPlace = function (otherVector) {
  2433. return this.divideToRef(otherVector, this);
  2434. };
  2435. /**
  2436. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  2437. * Returns the updated Vector3.
  2438. */
  2439. Vector3.prototype.MinimizeInPlace = function (other) {
  2440. if (other.x < this.x)
  2441. this.x = other.x;
  2442. if (other.y < this.y)
  2443. this.y = other.y;
  2444. if (other.z < this.z)
  2445. this.z = other.z;
  2446. return this;
  2447. };
  2448. /**
  2449. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  2450. * Returns the updated Vector3.
  2451. */
  2452. Vector3.prototype.MaximizeInPlace = function (other) {
  2453. if (other.x > this.x)
  2454. this.x = other.x;
  2455. if (other.y > this.y)
  2456. this.y = other.y;
  2457. if (other.z > this.z)
  2458. this.z = other.z;
  2459. return this;
  2460. };
  2461. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2462. /**
  2463. * Return true is the vector is non uniform meaning x, y or z are not all the same.
  2464. */
  2465. get: function () {
  2466. var absX = Math.abs(this.x);
  2467. var absY = Math.abs(this.y);
  2468. if (absX !== absY) {
  2469. return true;
  2470. }
  2471. var absZ = Math.abs(this.z);
  2472. if (absX !== absZ) {
  2473. return true;
  2474. }
  2475. if (absY !== absZ) {
  2476. return true;
  2477. }
  2478. return false;
  2479. },
  2480. enumerable: true,
  2481. configurable: true
  2482. });
  2483. // Properties
  2484. /**
  2485. * Returns the length of the Vector3 (float).
  2486. */
  2487. Vector3.prototype.length = function () {
  2488. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2489. };
  2490. /**
  2491. * Returns the squared length of the Vector3 (float).
  2492. */
  2493. Vector3.prototype.lengthSquared = function () {
  2494. return (this.x * this.x + this.y * this.y + this.z * this.z);
  2495. };
  2496. /**
  2497. * Normalize the current Vector3.
  2498. * Returns the updated Vector3.
  2499. * /!\ In place operation.
  2500. */
  2501. Vector3.prototype.normalize = function () {
  2502. var len = this.length();
  2503. if (len === 0 || len === 1.0)
  2504. return this;
  2505. var num = 1.0 / len;
  2506. this.x *= num;
  2507. this.y *= num;
  2508. this.z *= num;
  2509. return this;
  2510. };
  2511. /**
  2512. * Normalize the current Vector3 to a new vector.
  2513. * @returns the new Vector3.
  2514. */
  2515. Vector3.prototype.normalizeToNew = function () {
  2516. var normalized = new Vector3(0, 0, 0);
  2517. this.normalizeToRef(normalized);
  2518. return normalized;
  2519. };
  2520. /**
  2521. * Normalize the current Vector3 to the reference.
  2522. * @param the reference to update.
  2523. * @returns the updated Vector3.
  2524. */
  2525. Vector3.prototype.normalizeToRef = function (reference) {
  2526. var len = this.length();
  2527. if (len === 0 || len === 1.0) {
  2528. reference.set(this.x, this.y, this.z);
  2529. return reference;
  2530. }
  2531. var scale = 1.0 / len;
  2532. this.scaleToRef(scale, reference);
  2533. return reference;
  2534. };
  2535. /**
  2536. * Returns a new Vector3 copied from the current Vector3.
  2537. */
  2538. Vector3.prototype.clone = function () {
  2539. return new Vector3(this.x, this.y, this.z);
  2540. };
  2541. /**
  2542. * Copies the passed vector coordinates to the current Vector3 ones.
  2543. * Returns the updated Vector3.
  2544. */
  2545. Vector3.prototype.copyFrom = function (source) {
  2546. this.x = source.x;
  2547. this.y = source.y;
  2548. this.z = source.z;
  2549. return this;
  2550. };
  2551. /**
  2552. * Copies the passed floats to the current Vector3 coordinates.
  2553. * Returns the updated Vector3.
  2554. */
  2555. Vector3.prototype.copyFromFloats = function (x, y, z) {
  2556. this.x = x;
  2557. this.y = y;
  2558. this.z = z;
  2559. return this;
  2560. };
  2561. /**
  2562. * Copies the passed floats to the current Vector3 coordinates.
  2563. * Returns the updated Vector3.
  2564. */
  2565. Vector3.prototype.set = function (x, y, z) {
  2566. return this.copyFromFloats(x, y, z);
  2567. };
  2568. // Statics
  2569. /**
  2570. *
  2571. */
  2572. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  2573. var d0 = Vector3.Dot(vector0, axis) - size;
  2574. var d1 = Vector3.Dot(vector1, axis) - size;
  2575. var s = d0 / (d0 - d1);
  2576. return s;
  2577. };
  2578. /**
  2579. * Get angle between two vectors.
  2580. * @param vector0 angle between vector0 and vector1
  2581. * @param vector1 angle between vector0 and vector1
  2582. * @param normal direction of the normal.
  2583. * @return the angle between vector0 and vector1.
  2584. */
  2585. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  2586. var v0 = vector0.clone().normalize();
  2587. var v1 = vector1.clone().normalize();
  2588. var dot = Vector3.Dot(v0, v1);
  2589. var n = Vector3.Cross(v0, v1);
  2590. if (Vector3.Dot(n, normal) > 0) {
  2591. return Math.acos(dot);
  2592. }
  2593. return -Math.acos(dot);
  2594. };
  2595. /**
  2596. * Returns a new Vector3 set from the index "offset" of the passed array.
  2597. */
  2598. Vector3.FromArray = function (array, offset) {
  2599. if (!offset) {
  2600. offset = 0;
  2601. }
  2602. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  2603. };
  2604. /**
  2605. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  2606. * This function is deprecated. Use FromArray instead.
  2607. */
  2608. Vector3.FromFloatArray = function (array, offset) {
  2609. return Vector3.FromArray(array, offset);
  2610. };
  2611. /**
  2612. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  2613. */
  2614. Vector3.FromArrayToRef = function (array, offset, result) {
  2615. result.x = array[offset];
  2616. result.y = array[offset + 1];
  2617. result.z = array[offset + 2];
  2618. };
  2619. /**
  2620. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  2621. * This function is deprecated. Use FromArrayToRef instead.
  2622. */
  2623. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  2624. return Vector3.FromArrayToRef(array, offset, result);
  2625. };
  2626. /**
  2627. * Sets the passed vector "result" with the passed floats.
  2628. */
  2629. Vector3.FromFloatsToRef = function (x, y, z, result) {
  2630. result.x = x;
  2631. result.y = y;
  2632. result.z = z;
  2633. };
  2634. /**
  2635. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  2636. */
  2637. Vector3.Zero = function () {
  2638. return new Vector3(0.0, 0.0, 0.0);
  2639. };
  2640. /**
  2641. * Returns a new Vector3 set to (1.0, 1.0, 1.0).
  2642. */
  2643. Vector3.One = function () {
  2644. return new Vector3(1.0, 1.0, 1.0);
  2645. };
  2646. /**
  2647. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  2648. */
  2649. Vector3.Up = function () {
  2650. return new Vector3(0.0, 1.0, 0.0);
  2651. };
  2652. /**
  2653. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  2654. */
  2655. Vector3.Forward = function () {
  2656. return new Vector3(0.0, 0.0, 1.0);
  2657. };
  2658. /**
  2659. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  2660. */
  2661. Vector3.Right = function () {
  2662. return new Vector3(1.0, 0.0, 0.0);
  2663. };
  2664. /**
  2665. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  2666. */
  2667. Vector3.Left = function () {
  2668. return new Vector3(-1.0, 0.0, 0.0);
  2669. };
  2670. /**
  2671. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  2672. * This method computes tranformed coordinates only, not transformed direction vectors.
  2673. */
  2674. Vector3.TransformCoordinates = function (vector, transformation) {
  2675. var result = Vector3.Zero();
  2676. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  2677. return result;
  2678. };
  2679. /**
  2680. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  2681. * This method computes tranformed coordinates only, not transformed direction vectors.
  2682. */
  2683. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  2684. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  2685. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  2686. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  2687. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  2688. result.x = x / w;
  2689. result.y = y / w;
  2690. result.z = z / w;
  2691. };
  2692. /**
  2693. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  2694. * This method computes tranformed coordinates only, not transformed direction vectors.
  2695. */
  2696. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  2697. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  2698. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  2699. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  2700. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  2701. result.x = rx / rw;
  2702. result.y = ry / rw;
  2703. result.z = rz / rw;
  2704. };
  2705. /**
  2706. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  2707. * This methods computes transformed normalized direction vectors only.
  2708. */
  2709. Vector3.TransformNormal = function (vector, transformation) {
  2710. var result = Vector3.Zero();
  2711. Vector3.TransformNormalToRef(vector, transformation, result);
  2712. return result;
  2713. };
  2714. /**
  2715. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2716. * This methods computes transformed normalized direction vectors only.
  2717. */
  2718. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  2719. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2720. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2721. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2722. result.x = x;
  2723. result.y = y;
  2724. result.z = z;
  2725. };
  2726. /**
  2727. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  2728. * This methods computes transformed normalized direction vectors only.
  2729. */
  2730. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  2731. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2732. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2733. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2734. };
  2735. /**
  2736. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  2737. */
  2738. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  2739. var squared = amount * amount;
  2740. var cubed = amount * squared;
  2741. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2742. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2743. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2744. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2745. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2746. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2747. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  2748. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  2749. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  2750. return new Vector3(x, y, z);
  2751. };
  2752. /**
  2753. * 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".
  2754. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  2755. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  2756. */
  2757. Vector3.Clamp = function (value, min, max) {
  2758. var x = value.x;
  2759. x = (x > max.x) ? max.x : x;
  2760. x = (x < min.x) ? min.x : x;
  2761. var y = value.y;
  2762. y = (y > max.y) ? max.y : y;
  2763. y = (y < min.y) ? min.y : y;
  2764. var z = value.z;
  2765. z = (z > max.z) ? max.z : z;
  2766. z = (z < min.z) ? min.z : z;
  2767. return new Vector3(x, y, z);
  2768. };
  2769. /**
  2770. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2771. */
  2772. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2773. var squared = amount * amount;
  2774. var cubed = amount * squared;
  2775. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2776. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2777. var part3 = (cubed - (2.0 * squared)) + amount;
  2778. var part4 = cubed - squared;
  2779. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2780. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2781. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2782. return new Vector3(x, y, z);
  2783. };
  2784. /**
  2785. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  2786. */
  2787. Vector3.Lerp = function (start, end, amount) {
  2788. var result = new Vector3(0, 0, 0);
  2789. Vector3.LerpToRef(start, end, amount, result);
  2790. return result;
  2791. };
  2792. /**
  2793. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  2794. */
  2795. Vector3.LerpToRef = function (start, end, amount, result) {
  2796. result.x = start.x + ((end.x - start.x) * amount);
  2797. result.y = start.y + ((end.y - start.y) * amount);
  2798. result.z = start.z + ((end.z - start.z) * amount);
  2799. };
  2800. /**
  2801. * Returns the dot product (float) between the vectors "left" and "right".
  2802. */
  2803. Vector3.Dot = function (left, right) {
  2804. return (left.x * right.x + left.y * right.y + left.z * right.z);
  2805. };
  2806. /**
  2807. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  2808. * The cross product is then orthogonal to both "left" and "right".
  2809. */
  2810. Vector3.Cross = function (left, right) {
  2811. var result = Vector3.Zero();
  2812. Vector3.CrossToRef(left, right, result);
  2813. return result;
  2814. };
  2815. /**
  2816. * Sets the passed vector "result" with the cross product of "left" and "right".
  2817. * The cross product is then orthogonal to both "left" and "right".
  2818. */
  2819. Vector3.CrossToRef = function (left, right, result) {
  2820. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  2821. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  2822. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  2823. result.copyFrom(MathTmp.Vector3[0]);
  2824. };
  2825. /**
  2826. * Returns a new Vector3 as the normalization of the passed vector.
  2827. */
  2828. Vector3.Normalize = function (vector) {
  2829. var result = Vector3.Zero();
  2830. Vector3.NormalizeToRef(vector, result);
  2831. return result;
  2832. };
  2833. /**
  2834. * Sets the passed vector "result" with the normalization of the passed first vector.
  2835. */
  2836. Vector3.NormalizeToRef = function (vector, result) {
  2837. result.copyFrom(vector);
  2838. result.normalize();
  2839. };
  2840. Vector3.Project = function (vector, world, transform, viewport) {
  2841. var cw = viewport.width;
  2842. var ch = viewport.height;
  2843. var cx = viewport.x;
  2844. var cy = viewport.y;
  2845. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  2846. 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);
  2847. var matrix = MathTmp.Matrix[0];
  2848. world.multiplyToRef(transform, matrix);
  2849. matrix.multiplyToRef(viewportMatrix, matrix);
  2850. return Vector3.TransformCoordinates(vector, matrix);
  2851. };
  2852. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  2853. var matrix = MathTmp.Matrix[0];
  2854. world.multiplyToRef(transform, matrix);
  2855. matrix.invert();
  2856. source.x = source.x / viewportWidth * 2 - 1;
  2857. source.y = -(source.y / viewportHeight * 2 - 1);
  2858. var vector = Vector3.TransformCoordinates(source, matrix);
  2859. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  2860. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  2861. vector = vector.scale(1.0 / num);
  2862. }
  2863. return vector;
  2864. };
  2865. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  2866. var result = Vector3.Zero();
  2867. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  2868. return result;
  2869. };
  2870. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  2871. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  2872. };
  2873. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  2874. var matrix = MathTmp.Matrix[0];
  2875. world.multiplyToRef(view, matrix);
  2876. matrix.multiplyToRef(projection, matrix);
  2877. matrix.invert();
  2878. var screenSource = MathTmp.Vector3[0];
  2879. screenSource.x = sourceX / viewportWidth * 2 - 1;
  2880. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  2881. screenSource.z = 2 * sourceZ - 1.0;
  2882. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  2883. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  2884. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  2885. result.scaleInPlace(1.0 / num);
  2886. }
  2887. };
  2888. Vector3.Minimize = function (left, right) {
  2889. var min = left.clone();
  2890. min.MinimizeInPlace(right);
  2891. return min;
  2892. };
  2893. Vector3.Maximize = function (left, right) {
  2894. var max = left.clone();
  2895. max.MaximizeInPlace(right);
  2896. return max;
  2897. };
  2898. /**
  2899. * Returns the distance (float) between the vectors "value1" and "value2".
  2900. */
  2901. Vector3.Distance = function (value1, value2) {
  2902. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  2903. };
  2904. /**
  2905. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2906. */
  2907. Vector3.DistanceSquared = function (value1, value2) {
  2908. var x = value1.x - value2.x;
  2909. var y = value1.y - value2.y;
  2910. var z = value1.z - value2.z;
  2911. return (x * x) + (y * y) + (z * z);
  2912. };
  2913. /**
  2914. * Returns a new Vector3 located at the center between "value1" and "value2".
  2915. */
  2916. Vector3.Center = function (value1, value2) {
  2917. var center = value1.add(value2);
  2918. center.scaleInPlace(0.5);
  2919. return center;
  2920. };
  2921. /**
  2922. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  2923. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  2924. * to something in order to rotate it from its local system to the given target system.
  2925. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2926. * Returns a new Vector3.
  2927. */
  2928. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  2929. var rotation = Vector3.Zero();
  2930. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  2931. return rotation;
  2932. };
  2933. /**
  2934. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  2935. */
  2936. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2937. var quat = MathTmp.Quaternion[0];
  2938. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2939. quat.toEulerAnglesToRef(ref);
  2940. };
  2941. return Vector3;
  2942. }());
  2943. BABYLON.Vector3 = Vector3;
  2944. //Vector4 class created for EulerAngle class conversion to Quaternion
  2945. var Vector4 = /** @class */ (function () {
  2946. /**
  2947. * Creates a Vector4 object from the passed floats.
  2948. */
  2949. function Vector4(x, y, z, w) {
  2950. this.x = x;
  2951. this.y = y;
  2952. this.z = z;
  2953. this.w = w;
  2954. }
  2955. /**
  2956. * Returns the string with the Vector4 coordinates.
  2957. */
  2958. Vector4.prototype.toString = function () {
  2959. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2960. };
  2961. /**
  2962. * Returns the string "Vector4".
  2963. */
  2964. Vector4.prototype.getClassName = function () {
  2965. return "Vector4";
  2966. };
  2967. /**
  2968. * Returns the Vector4 hash code.
  2969. */
  2970. Vector4.prototype.getHashCode = function () {
  2971. var hash = this.x || 0;
  2972. hash = (hash * 397) ^ (this.y || 0);
  2973. hash = (hash * 397) ^ (this.z || 0);
  2974. hash = (hash * 397) ^ (this.w || 0);
  2975. return hash;
  2976. };
  2977. // Operators
  2978. /**
  2979. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  2980. */
  2981. Vector4.prototype.asArray = function () {
  2982. var result = new Array();
  2983. this.toArray(result, 0);
  2984. return result;
  2985. };
  2986. /**
  2987. * Populates the passed array from the passed index with the Vector4 coordinates.
  2988. * Returns the Vector4.
  2989. */
  2990. Vector4.prototype.toArray = function (array, index) {
  2991. if (index === undefined) {
  2992. index = 0;
  2993. }
  2994. array[index] = this.x;
  2995. array[index + 1] = this.y;
  2996. array[index + 2] = this.z;
  2997. array[index + 3] = this.w;
  2998. return this;
  2999. };
  3000. /**
  3001. * Adds the passed vector to the current Vector4.
  3002. * Returns the updated Vector4.
  3003. */
  3004. Vector4.prototype.addInPlace = function (otherVector) {
  3005. this.x += otherVector.x;
  3006. this.y += otherVector.y;
  3007. this.z += otherVector.z;
  3008. this.w += otherVector.w;
  3009. return this;
  3010. };
  3011. /**
  3012. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  3013. */
  3014. Vector4.prototype.add = function (otherVector) {
  3015. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3016. };
  3017. /**
  3018. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3019. * Returns the current Vector4.
  3020. */
  3021. Vector4.prototype.addToRef = function (otherVector, result) {
  3022. result.x = this.x + otherVector.x;
  3023. result.y = this.y + otherVector.y;
  3024. result.z = this.z + otherVector.z;
  3025. result.w = this.w + otherVector.w;
  3026. return this;
  3027. };
  3028. /**
  3029. * Subtract in place the passed vector from the current Vector4.
  3030. * Returns the updated Vector4.
  3031. */
  3032. Vector4.prototype.subtractInPlace = function (otherVector) {
  3033. this.x -= otherVector.x;
  3034. this.y -= otherVector.y;
  3035. this.z -= otherVector.z;
  3036. this.w -= otherVector.w;
  3037. return this;
  3038. };
  3039. /**
  3040. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3041. */
  3042. Vector4.prototype.subtract = function (otherVector) {
  3043. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3044. };
  3045. /**
  3046. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3047. * Returns the current Vector4.
  3048. */
  3049. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3050. result.x = this.x - otherVector.x;
  3051. result.y = this.y - otherVector.y;
  3052. result.z = this.z - otherVector.z;
  3053. result.w = this.w - otherVector.w;
  3054. return this;
  3055. };
  3056. /**
  3057. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3058. */
  3059. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3060. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3061. };
  3062. /**
  3063. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3064. * Returns the current Vector4.
  3065. */
  3066. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3067. result.x = this.x - x;
  3068. result.y = this.y - y;
  3069. result.z = this.z - z;
  3070. result.w = this.w - w;
  3071. return this;
  3072. };
  3073. /**
  3074. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3075. */
  3076. Vector4.prototype.negate = function () {
  3077. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3078. };
  3079. /**
  3080. * Multiplies the current Vector4 coordinates by scale (float).
  3081. * Returns the updated Vector4.
  3082. */
  3083. Vector4.prototype.scaleInPlace = function (scale) {
  3084. this.x *= scale;
  3085. this.y *= scale;
  3086. this.z *= scale;
  3087. this.w *= scale;
  3088. return this;
  3089. };
  3090. /**
  3091. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3092. */
  3093. Vector4.prototype.scale = function (scale) {
  3094. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3095. };
  3096. /**
  3097. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3098. * Returns the current Vector4.
  3099. */
  3100. Vector4.prototype.scaleToRef = function (scale, result) {
  3101. result.x = this.x * scale;
  3102. result.y = this.y * scale;
  3103. result.z = this.z * scale;
  3104. result.w = this.w * scale;
  3105. return this;
  3106. };
  3107. /**
  3108. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3109. */
  3110. Vector4.prototype.equals = function (otherVector) {
  3111. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3112. };
  3113. /**
  3114. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3115. */
  3116. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3117. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3118. return otherVector
  3119. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3120. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3121. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3122. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3123. };
  3124. /**
  3125. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3126. */
  3127. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3128. return this.x === x && this.y === y && this.z === z && this.w === w;
  3129. };
  3130. /**
  3131. * Multiplies in place the current Vector4 by the passed one.
  3132. * Returns the updated Vector4.
  3133. */
  3134. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3135. this.x *= otherVector.x;
  3136. this.y *= otherVector.y;
  3137. this.z *= otherVector.z;
  3138. this.w *= otherVector.w;
  3139. return this;
  3140. };
  3141. /**
  3142. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3143. */
  3144. Vector4.prototype.multiply = function (otherVector) {
  3145. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3146. };
  3147. /**
  3148. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3149. * Returns the current Vector4.
  3150. */
  3151. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3152. result.x = this.x * otherVector.x;
  3153. result.y = this.y * otherVector.y;
  3154. result.z = this.z * otherVector.z;
  3155. result.w = this.w * otherVector.w;
  3156. return this;
  3157. };
  3158. /**
  3159. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  3160. */
  3161. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3162. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3163. };
  3164. /**
  3165. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  3166. */
  3167. Vector4.prototype.divide = function (otherVector) {
  3168. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3169. };
  3170. /**
  3171. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  3172. * Returns the current Vector4.
  3173. */
  3174. Vector4.prototype.divideToRef = function (otherVector, result) {
  3175. result.x = this.x / otherVector.x;
  3176. result.y = this.y / otherVector.y;
  3177. result.z = this.z / otherVector.z;
  3178. result.w = this.w / otherVector.w;
  3179. return this;
  3180. };
  3181. /**
  3182. * Divides the current Vector3 coordinates by the passed ones.
  3183. * Returns the updated Vector3.
  3184. */
  3185. Vector4.prototype.divideInPlace = function (otherVector) {
  3186. return this.divideToRef(otherVector, this);
  3187. };
  3188. /**
  3189. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  3190. */
  3191. Vector4.prototype.MinimizeInPlace = function (other) {
  3192. if (other.x < this.x)
  3193. this.x = other.x;
  3194. if (other.y < this.y)
  3195. this.y = other.y;
  3196. if (other.z < this.z)
  3197. this.z = other.z;
  3198. if (other.w < this.w)
  3199. this.w = other.w;
  3200. return this;
  3201. };
  3202. /**
  3203. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  3204. */
  3205. Vector4.prototype.MaximizeInPlace = function (other) {
  3206. if (other.x > this.x)
  3207. this.x = other.x;
  3208. if (other.y > this.y)
  3209. this.y = other.y;
  3210. if (other.z > this.z)
  3211. this.z = other.z;
  3212. if (other.w > this.w)
  3213. this.w = other.w;
  3214. return this;
  3215. };
  3216. // Properties
  3217. /**
  3218. * Returns the Vector4 length (float).
  3219. */
  3220. Vector4.prototype.length = function () {
  3221. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3222. };
  3223. /**
  3224. * Returns the Vector4 squared length (float).
  3225. */
  3226. Vector4.prototype.lengthSquared = function () {
  3227. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3228. };
  3229. // Methods
  3230. /**
  3231. * Normalizes in place the Vector4.
  3232. * Returns the updated Vector4.
  3233. */
  3234. Vector4.prototype.normalize = function () {
  3235. var len = this.length();
  3236. if (len === 0)
  3237. return this;
  3238. var num = 1.0 / len;
  3239. this.x *= num;
  3240. this.y *= num;
  3241. this.z *= num;
  3242. this.w *= num;
  3243. return this;
  3244. };
  3245. /**
  3246. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3247. */
  3248. Vector4.prototype.toVector3 = function () {
  3249. return new Vector3(this.x, this.y, this.z);
  3250. };
  3251. /**
  3252. * Returns a new Vector4 copied from the current one.
  3253. */
  3254. Vector4.prototype.clone = function () {
  3255. return new Vector4(this.x, this.y, this.z, this.w);
  3256. };
  3257. /**
  3258. * Updates the current Vector4 with the passed one coordinates.
  3259. * Returns the updated Vector4.
  3260. */
  3261. Vector4.prototype.copyFrom = function (source) {
  3262. this.x = source.x;
  3263. this.y = source.y;
  3264. this.z = source.z;
  3265. this.w = source.w;
  3266. return this;
  3267. };
  3268. /**
  3269. * Updates the current Vector4 coordinates with the passed floats.
  3270. * Returns the updated Vector4.
  3271. */
  3272. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3273. this.x = x;
  3274. this.y = y;
  3275. this.z = z;
  3276. this.w = w;
  3277. return this;
  3278. };
  3279. /**
  3280. * Updates the current Vector4 coordinates with the passed floats.
  3281. * Returns the updated Vector4.
  3282. */
  3283. Vector4.prototype.set = function (x, y, z, w) {
  3284. return this.copyFromFloats(x, y, z, w);
  3285. };
  3286. // Statics
  3287. /**
  3288. * Returns a new Vector4 set from the starting index of the passed array.
  3289. */
  3290. Vector4.FromArray = function (array, offset) {
  3291. if (!offset) {
  3292. offset = 0;
  3293. }
  3294. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3295. };
  3296. /**
  3297. * Updates the passed vector "result" from the starting index of the passed array.
  3298. */
  3299. Vector4.FromArrayToRef = function (array, offset, result) {
  3300. result.x = array[offset];
  3301. result.y = array[offset + 1];
  3302. result.z = array[offset + 2];
  3303. result.w = array[offset + 3];
  3304. };
  3305. /**
  3306. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  3307. */
  3308. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  3309. Vector4.FromArrayToRef(array, offset, result);
  3310. };
  3311. /**
  3312. * Updates the passed vector "result" coordinates from the passed floats.
  3313. */
  3314. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  3315. result.x = x;
  3316. result.y = y;
  3317. result.z = z;
  3318. result.w = w;
  3319. };
  3320. /**
  3321. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  3322. */
  3323. Vector4.Zero = function () {
  3324. return new Vector4(0.0, 0.0, 0.0, 0.0);
  3325. };
  3326. /**
  3327. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  3328. */
  3329. Vector4.One = function () {
  3330. return new Vector4(1.0, 1.0, 1.0, 1.0);
  3331. };
  3332. /**
  3333. * Returns a new normalized Vector4 from the passed one.
  3334. */
  3335. Vector4.Normalize = function (vector) {
  3336. var result = Vector4.Zero();
  3337. Vector4.NormalizeToRef(vector, result);
  3338. return result;
  3339. };
  3340. /**
  3341. * Updates the passed vector "result" from the normalization of the passed one.
  3342. */
  3343. Vector4.NormalizeToRef = function (vector, result) {
  3344. result.copyFrom(vector);
  3345. result.normalize();
  3346. };
  3347. Vector4.Minimize = function (left, right) {
  3348. var min = left.clone();
  3349. min.MinimizeInPlace(right);
  3350. return min;
  3351. };
  3352. Vector4.Maximize = function (left, right) {
  3353. var max = left.clone();
  3354. max.MaximizeInPlace(right);
  3355. return max;
  3356. };
  3357. /**
  3358. * Returns the distance (float) between the vectors "value1" and "value2".
  3359. */
  3360. Vector4.Distance = function (value1, value2) {
  3361. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  3362. };
  3363. /**
  3364. * Returns the squared distance (float) between the vectors "value1" and "value2".
  3365. */
  3366. Vector4.DistanceSquared = function (value1, value2) {
  3367. var x = value1.x - value2.x;
  3368. var y = value1.y - value2.y;
  3369. var z = value1.z - value2.z;
  3370. var w = value1.w - value2.w;
  3371. return (x * x) + (y * y) + (z * z) + (w * w);
  3372. };
  3373. /**
  3374. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  3375. */
  3376. Vector4.Center = function (value1, value2) {
  3377. var center = value1.add(value2);
  3378. center.scaleInPlace(0.5);
  3379. return center;
  3380. };
  3381. /**
  3382. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  3383. * This methods computes transformed normalized direction vectors only.
  3384. */
  3385. Vector4.TransformNormal = function (vector, transformation) {
  3386. var result = Vector4.Zero();
  3387. Vector4.TransformNormalToRef(vector, transformation, result);
  3388. return result;
  3389. };
  3390. /**
  3391. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  3392. * This methods computes transformed normalized direction vectors only.
  3393. */
  3394. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  3395. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3396. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3397. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3398. result.x = x;
  3399. result.y = y;
  3400. result.z = z;
  3401. result.w = vector.w;
  3402. };
  3403. /**
  3404. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  3405. * This methods computes transformed normalized direction vectors only.
  3406. */
  3407. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  3408. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3409. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3410. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3411. result.w = w;
  3412. };
  3413. return Vector4;
  3414. }());
  3415. BABYLON.Vector4 = Vector4;
  3416. var Size = /** @class */ (function () {
  3417. /**
  3418. * Creates a Size object from the passed width and height (floats).
  3419. */
  3420. function Size(width, height) {
  3421. this.width = width;
  3422. this.height = height;
  3423. }
  3424. // Returns a string with the Size width and height.
  3425. Size.prototype.toString = function () {
  3426. return "{W: " + this.width + ", H: " + this.height + "}";
  3427. };
  3428. /**
  3429. * Returns the string "Size"
  3430. */
  3431. Size.prototype.getClassName = function () {
  3432. return "Size";
  3433. };
  3434. /**
  3435. * Returns the Size hash code.
  3436. */
  3437. Size.prototype.getHashCode = function () {
  3438. var hash = this.width || 0;
  3439. hash = (hash * 397) ^ (this.height || 0);
  3440. return hash;
  3441. };
  3442. /**
  3443. * Updates the current size from the passed one.
  3444. * Returns the updated Size.
  3445. */
  3446. Size.prototype.copyFrom = function (src) {
  3447. this.width = src.width;
  3448. this.height = src.height;
  3449. };
  3450. /**
  3451. * Updates in place the current Size from the passed floats.
  3452. * Returns the updated Size.
  3453. */
  3454. Size.prototype.copyFromFloats = function (width, height) {
  3455. this.width = width;
  3456. this.height = height;
  3457. return this;
  3458. };
  3459. /**
  3460. * Updates in place the current Size from the passed floats.
  3461. * Returns the updated Size.
  3462. */
  3463. Size.prototype.set = function (width, height) {
  3464. return this.copyFromFloats(width, height);
  3465. };
  3466. /**
  3467. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  3468. */
  3469. Size.prototype.multiplyByFloats = function (w, h) {
  3470. return new Size(this.width * w, this.height * h);
  3471. };
  3472. /**
  3473. * Returns a new Size copied from the passed one.
  3474. */
  3475. Size.prototype.clone = function () {
  3476. return new Size(this.width, this.height);
  3477. };
  3478. /**
  3479. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  3480. */
  3481. Size.prototype.equals = function (other) {
  3482. if (!other) {
  3483. return false;
  3484. }
  3485. return (this.width === other.width) && (this.height === other.height);
  3486. };
  3487. Object.defineProperty(Size.prototype, "surface", {
  3488. /**
  3489. * Returns the surface of the Size : width * height (float).
  3490. */
  3491. get: function () {
  3492. return this.width * this.height;
  3493. },
  3494. enumerable: true,
  3495. configurable: true
  3496. });
  3497. /**
  3498. * Returns a new Size set to (0.0, 0.0)
  3499. */
  3500. Size.Zero = function () {
  3501. return new Size(0.0, 0.0);
  3502. };
  3503. /**
  3504. * Returns a new Size set as the addition result of the current Size and the passed one.
  3505. */
  3506. Size.prototype.add = function (otherSize) {
  3507. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  3508. return r;
  3509. };
  3510. /**
  3511. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  3512. */
  3513. Size.prototype.subtract = function (otherSize) {
  3514. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  3515. return r;
  3516. };
  3517. /**
  3518. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  3519. */
  3520. Size.Lerp = function (start, end, amount) {
  3521. var w = start.width + ((end.width - start.width) * amount);
  3522. var h = start.height + ((end.height - start.height) * amount);
  3523. return new Size(w, h);
  3524. };
  3525. return Size;
  3526. }());
  3527. BABYLON.Size = Size;
  3528. var Quaternion = /** @class */ (function () {
  3529. /**
  3530. * Creates a new Quaternion from the passed floats.
  3531. */
  3532. function Quaternion(x, y, z, w) {
  3533. if (x === void 0) { x = 0.0; }
  3534. if (y === void 0) { y = 0.0; }
  3535. if (z === void 0) { z = 0.0; }
  3536. if (w === void 0) { w = 1.0; }
  3537. this.x = x;
  3538. this.y = y;
  3539. this.z = z;
  3540. this.w = w;
  3541. }
  3542. /**
  3543. * Returns a string with the Quaternion coordinates.
  3544. */
  3545. Quaternion.prototype.toString = function () {
  3546. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3547. };
  3548. /**
  3549. * Returns the string "Quaternion".
  3550. */
  3551. Quaternion.prototype.getClassName = function () {
  3552. return "Quaternion";
  3553. };
  3554. /**
  3555. * Returns the Quaternion hash code.
  3556. */
  3557. Quaternion.prototype.getHashCode = function () {
  3558. var hash = this.x || 0;
  3559. hash = (hash * 397) ^ (this.y || 0);
  3560. hash = (hash * 397) ^ (this.z || 0);
  3561. hash = (hash * 397) ^ (this.w || 0);
  3562. return hash;
  3563. };
  3564. /**
  3565. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  3566. */
  3567. Quaternion.prototype.asArray = function () {
  3568. return [this.x, this.y, this.z, this.w];
  3569. };
  3570. /**
  3571. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  3572. */
  3573. Quaternion.prototype.equals = function (otherQuaternion) {
  3574. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  3575. };
  3576. /**
  3577. * Returns a new Quaternion copied from the current one.
  3578. */
  3579. Quaternion.prototype.clone = function () {
  3580. return new Quaternion(this.x, this.y, this.z, this.w);
  3581. };
  3582. /**
  3583. * Updates the current Quaternion from the passed one coordinates.
  3584. * Returns the updated Quaterion.
  3585. */
  3586. Quaternion.prototype.copyFrom = function (other) {
  3587. this.x = other.x;
  3588. this.y = other.y;
  3589. this.z = other.z;
  3590. this.w = other.w;
  3591. return this;
  3592. };
  3593. /**
  3594. * Updates the current Quaternion from the passed float coordinates.
  3595. * Returns the updated Quaterion.
  3596. */
  3597. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  3598. this.x = x;
  3599. this.y = y;
  3600. this.z = z;
  3601. this.w = w;
  3602. return this;
  3603. };
  3604. /**
  3605. * Updates the current Quaternion from the passed float coordinates.
  3606. * Returns the updated Quaterion.
  3607. */
  3608. Quaternion.prototype.set = function (x, y, z, w) {
  3609. return this.copyFromFloats(x, y, z, w);
  3610. };
  3611. /**
  3612. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  3613. */
  3614. Quaternion.prototype.add = function (other) {
  3615. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  3616. };
  3617. /**
  3618. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  3619. */
  3620. Quaternion.prototype.subtract = function (other) {
  3621. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  3622. };
  3623. /**
  3624. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  3625. */
  3626. Quaternion.prototype.scale = function (value) {
  3627. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  3628. };
  3629. /**
  3630. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  3631. */
  3632. Quaternion.prototype.multiply = function (q1) {
  3633. var result = new Quaternion(0, 0, 0, 1.0);
  3634. this.multiplyToRef(q1, result);
  3635. return result;
  3636. };
  3637. /**
  3638. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  3639. * Returns the current Quaternion.
  3640. */
  3641. Quaternion.prototype.multiplyToRef = function (q1, result) {
  3642. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  3643. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  3644. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  3645. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  3646. result.copyFromFloats(x, y, z, w);
  3647. return this;
  3648. };
  3649. /**
  3650. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  3651. * Returns the updated Quaternion.
  3652. */
  3653. Quaternion.prototype.multiplyInPlace = function (q1) {
  3654. this.multiplyToRef(q1, this);
  3655. return this;
  3656. };
  3657. /**
  3658. * Sets the passed "ref" with the conjugation of the current Quaternion.
  3659. * Returns the current Quaternion.
  3660. */
  3661. Quaternion.prototype.conjugateToRef = function (ref) {
  3662. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  3663. return this;
  3664. };
  3665. /**
  3666. * Conjugates in place the current Quaternion.
  3667. * Returns the updated Quaternion.
  3668. */
  3669. Quaternion.prototype.conjugateInPlace = function () {
  3670. this.x *= -1;
  3671. this.y *= -1;
  3672. this.z *= -1;
  3673. return this;
  3674. };
  3675. /**
  3676. * Returns a new Quaternion as the conjugate of the current Quaternion.
  3677. */
  3678. Quaternion.prototype.conjugate = function () {
  3679. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  3680. return result;
  3681. };
  3682. /**
  3683. * Returns the Quaternion length (float).
  3684. */
  3685. Quaternion.prototype.length = function () {
  3686. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  3687. };
  3688. /**
  3689. * Normalize in place the current Quaternion.
  3690. * Returns the updated Quaternion.
  3691. */
  3692. Quaternion.prototype.normalize = function () {
  3693. var length = 1.0 / this.length();
  3694. this.x *= length;
  3695. this.y *= length;
  3696. this.z *= length;
  3697. this.w *= length;
  3698. return this;
  3699. };
  3700. /**
  3701. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  3702. */
  3703. Quaternion.prototype.toEulerAngles = function (order) {
  3704. if (order === void 0) { order = "YZX"; }
  3705. var result = Vector3.Zero();
  3706. this.toEulerAnglesToRef(result, order);
  3707. return result;
  3708. };
  3709. /**
  3710. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  3711. * Returns the current Quaternion.
  3712. */
  3713. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  3714. if (order === void 0) { order = "YZX"; }
  3715. var qz = this.z;
  3716. var qx = this.x;
  3717. var qy = this.y;
  3718. var qw = this.w;
  3719. var sqw = qw * qw;
  3720. var sqz = qz * qz;
  3721. var sqx = qx * qx;
  3722. var sqy = qy * qy;
  3723. var zAxisY = qy * qz - qx * qw;
  3724. var limit = .4999999;
  3725. if (zAxisY < -limit) {
  3726. result.y = 2 * Math.atan2(qy, qw);
  3727. result.x = Math.PI / 2;
  3728. result.z = 0;
  3729. }
  3730. else if (zAxisY > limit) {
  3731. result.y = 2 * Math.atan2(qy, qw);
  3732. result.x = -Math.PI / 2;
  3733. result.z = 0;
  3734. }
  3735. else {
  3736. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  3737. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  3738. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  3739. }
  3740. return this;
  3741. };
  3742. /**
  3743. * Updates the passed rotation matrix with the current Quaternion values.
  3744. * Returns the current Quaternion.
  3745. */
  3746. Quaternion.prototype.toRotationMatrix = function (result) {
  3747. var xx = this.x * this.x;
  3748. var yy = this.y * this.y;
  3749. var zz = this.z * this.z;
  3750. var xy = this.x * this.y;
  3751. var zw = this.z * this.w;
  3752. var zx = this.z * this.x;
  3753. var yw = this.y * this.w;
  3754. var yz = this.y * this.z;
  3755. var xw = this.x * this.w;
  3756. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3757. result.m[1] = 2.0 * (xy + zw);
  3758. result.m[2] = 2.0 * (zx - yw);
  3759. result.m[3] = 0;
  3760. result.m[4] = 2.0 * (xy - zw);
  3761. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3762. result.m[6] = 2.0 * (yz + xw);
  3763. result.m[7] = 0;
  3764. result.m[8] = 2.0 * (zx + yw);
  3765. result.m[9] = 2.0 * (yz - xw);
  3766. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3767. result.m[11] = 0;
  3768. result.m[12] = 0;
  3769. result.m[13] = 0;
  3770. result.m[14] = 0;
  3771. result.m[15] = 1.0;
  3772. result._markAsUpdated();
  3773. return this;
  3774. };
  3775. /**
  3776. * Updates the current Quaternion from the passed rotation matrix values.
  3777. * Returns the updated Quaternion.
  3778. */
  3779. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  3780. Quaternion.FromRotationMatrixToRef(matrix, this);
  3781. return this;
  3782. };
  3783. // Statics
  3784. /**
  3785. * Returns a new Quaternion set from the passed rotation matrix values.
  3786. */
  3787. Quaternion.FromRotationMatrix = function (matrix) {
  3788. var result = new Quaternion();
  3789. Quaternion.FromRotationMatrixToRef(matrix, result);
  3790. return result;
  3791. };
  3792. /**
  3793. * Updates the passed quaternion "result" with the passed rotation matrix values.
  3794. */
  3795. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  3796. var data = matrix.m;
  3797. var m11 = data[0], m12 = data[4], m13 = data[8];
  3798. var m21 = data[1], m22 = data[5], m23 = data[9];
  3799. var m31 = data[2], m32 = data[6], m33 = data[10];
  3800. var trace = m11 + m22 + m33;
  3801. var s;
  3802. if (trace > 0) {
  3803. s = 0.5 / Math.sqrt(trace + 1.0);
  3804. result.w = 0.25 / s;
  3805. result.x = (m32 - m23) * s;
  3806. result.y = (m13 - m31) * s;
  3807. result.z = (m21 - m12) * s;
  3808. }
  3809. else if (m11 > m22 && m11 > m33) {
  3810. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  3811. result.w = (m32 - m23) / s;
  3812. result.x = 0.25 * s;
  3813. result.y = (m12 + m21) / s;
  3814. result.z = (m13 + m31) / s;
  3815. }
  3816. else if (m22 > m33) {
  3817. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  3818. result.w = (m13 - m31) / s;
  3819. result.x = (m12 + m21) / s;
  3820. result.y = 0.25 * s;
  3821. result.z = (m23 + m32) / s;
  3822. }
  3823. else {
  3824. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  3825. result.w = (m21 - m12) / s;
  3826. result.x = (m13 + m31) / s;
  3827. result.y = (m23 + m32) / s;
  3828. result.z = 0.25 * s;
  3829. }
  3830. };
  3831. /**
  3832. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  3833. */
  3834. Quaternion.Zero = function () {
  3835. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  3836. };
  3837. /**
  3838. * Returns a new Quaternion as the inverted current Quaternion.
  3839. */
  3840. Quaternion.Inverse = function (q) {
  3841. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  3842. };
  3843. /**
  3844. * Returns the identity Quaternion.
  3845. */
  3846. Quaternion.Identity = function () {
  3847. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  3848. };
  3849. Quaternion.IsIdentity = function (quaternion) {
  3850. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  3851. };
  3852. /**
  3853. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  3854. */
  3855. Quaternion.RotationAxis = function (axis, angle) {
  3856. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  3857. };
  3858. /**
  3859. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  3860. */
  3861. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  3862. var sin = Math.sin(angle / 2);
  3863. axis.normalize();
  3864. result.w = Math.cos(angle / 2);
  3865. result.x = axis.x * sin;
  3866. result.y = axis.y * sin;
  3867. result.z = axis.z * sin;
  3868. return result;
  3869. };
  3870. /**
  3871. * Retuns a new Quaternion set from the starting index of the passed array.
  3872. */
  3873. Quaternion.FromArray = function (array, offset) {
  3874. if (!offset) {
  3875. offset = 0;
  3876. }
  3877. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3878. };
  3879. /**
  3880. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  3881. */
  3882. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3883. var q = new Quaternion();
  3884. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  3885. return q;
  3886. };
  3887. /**
  3888. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  3889. */
  3890. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3891. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  3892. var halfRoll = roll * 0.5;
  3893. var halfPitch = pitch * 0.5;
  3894. var halfYaw = yaw * 0.5;
  3895. var sinRoll = Math.sin(halfRoll);
  3896. var cosRoll = Math.cos(halfRoll);
  3897. var sinPitch = Math.sin(halfPitch);
  3898. var cosPitch = Math.cos(halfPitch);
  3899. var sinYaw = Math.sin(halfYaw);
  3900. var cosYaw = Math.cos(halfYaw);
  3901. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  3902. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  3903. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  3904. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  3905. };
  3906. /**
  3907. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  3908. */
  3909. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  3910. var result = new Quaternion();
  3911. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  3912. return result;
  3913. };
  3914. /**
  3915. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  3916. */
  3917. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  3918. // Produces a quaternion from Euler angles in the z-x-z orientation
  3919. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  3920. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  3921. var halfBeta = beta * 0.5;
  3922. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  3923. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  3924. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  3925. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  3926. };
  3927. /**
  3928. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  3929. * cf to Vector3.RotationFromAxis() documentation.
  3930. * Note : axis1, axis2 and axis3 are normalized during this operation.
  3931. */
  3932. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  3933. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  3934. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3935. return quat;
  3936. };
  3937. /**
  3938. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  3939. * cf to Vector3.RotationFromAxis() documentation.
  3940. * Note : axis1, axis2 and axis3 are normalized during this operation.
  3941. */
  3942. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3943. var rotMat = MathTmp.Matrix[0];
  3944. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  3945. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  3946. };
  3947. Quaternion.Slerp = function (left, right, amount) {
  3948. var result = Quaternion.Identity();
  3949. Quaternion.SlerpToRef(left, right, amount, result);
  3950. return result;
  3951. };
  3952. Quaternion.SlerpToRef = function (left, right, amount, result) {
  3953. var num2;
  3954. var num3;
  3955. var num = amount;
  3956. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  3957. var flag = false;
  3958. if (num4 < 0) {
  3959. flag = true;
  3960. num4 = -num4;
  3961. }
  3962. if (num4 > 0.999999) {
  3963. num3 = 1 - num;
  3964. num2 = flag ? -num : num;
  3965. }
  3966. else {
  3967. var num5 = Math.acos(num4);
  3968. var num6 = (1.0 / Math.sin(num5));
  3969. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  3970. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  3971. }
  3972. result.x = (num3 * left.x) + (num2 * right.x);
  3973. result.y = (num3 * left.y) + (num2 * right.y);
  3974. result.z = (num3 * left.z) + (num2 * right.z);
  3975. result.w = (num3 * left.w) + (num2 * right.w);
  3976. };
  3977. /**
  3978. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  3979. */
  3980. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3981. var squared = amount * amount;
  3982. var cubed = amount * squared;
  3983. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3984. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3985. var part3 = (cubed - (2.0 * squared)) + amount;
  3986. var part4 = cubed - squared;
  3987. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3988. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3989. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3990. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  3991. return new Quaternion(x, y, z, w);
  3992. };
  3993. return Quaternion;
  3994. }());
  3995. BABYLON.Quaternion = Quaternion;
  3996. var Matrix = /** @class */ (function () {
  3997. function Matrix() {
  3998. this._isIdentity = false;
  3999. this._isIdentityDirty = true;
  4000. this.m = new Float32Array(16);
  4001. this._markAsUpdated();
  4002. }
  4003. Matrix.prototype._markAsUpdated = function () {
  4004. this.updateFlag = Matrix._updateFlagSeed++;
  4005. this._isIdentityDirty = true;
  4006. };
  4007. // Properties
  4008. /**
  4009. * Boolean : True is the matrix is the identity matrix
  4010. */
  4011. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4012. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4013. if (this._isIdentityDirty) {
  4014. this._isIdentityDirty = false;
  4015. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4016. this._isIdentity = false;
  4017. }
  4018. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4019. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4020. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4021. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4022. this._isIdentity = false;
  4023. }
  4024. else {
  4025. this._isIdentity = true;
  4026. }
  4027. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4028. this._isIdentity = false;
  4029. }
  4030. }
  4031. return this._isIdentity;
  4032. };
  4033. /**
  4034. * Returns the matrix determinant (float).
  4035. */
  4036. Matrix.prototype.determinant = function () {
  4037. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4038. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4039. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4040. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4041. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4042. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4043. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4044. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4045. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4046. };
  4047. // Methods
  4048. /**
  4049. * Returns the matrix underlying array.
  4050. */
  4051. Matrix.prototype.toArray = function () {
  4052. return this.m;
  4053. };
  4054. /**
  4055. * Returns the matrix underlying array.
  4056. */
  4057. Matrix.prototype.asArray = function () {
  4058. return this.toArray();
  4059. };
  4060. /**
  4061. * Inverts in place the Matrix.
  4062. * Returns the Matrix inverted.
  4063. */
  4064. Matrix.prototype.invert = function () {
  4065. this.invertToRef(this);
  4066. return this;
  4067. };
  4068. /**
  4069. * Sets all the matrix elements to zero.
  4070. * Returns the Matrix.
  4071. */
  4072. Matrix.prototype.reset = function () {
  4073. for (var index = 0; index < 16; index++) {
  4074. this.m[index] = 0.0;
  4075. }
  4076. this._markAsUpdated();
  4077. return this;
  4078. };
  4079. /**
  4080. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  4081. */
  4082. Matrix.prototype.add = function (other) {
  4083. var result = new Matrix();
  4084. this.addToRef(other, result);
  4085. return result;
  4086. };
  4087. /**
  4088. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  4089. * Returns the Matrix.
  4090. */
  4091. Matrix.prototype.addToRef = function (other, result) {
  4092. for (var index = 0; index < 16; index++) {
  4093. result.m[index] = this.m[index] + other.m[index];
  4094. }
  4095. result._markAsUpdated();
  4096. return this;
  4097. };
  4098. /**
  4099. * Adds in place the passed matrix to the current Matrix.
  4100. * Returns the updated Matrix.
  4101. */
  4102. Matrix.prototype.addToSelf = function (other) {
  4103. for (var index = 0; index < 16; index++) {
  4104. this.m[index] += other.m[index];
  4105. }
  4106. this._markAsUpdated();
  4107. return this;
  4108. };
  4109. /**
  4110. * Sets the passed matrix with the current inverted Matrix.
  4111. * Returns the unmodified current Matrix.
  4112. */
  4113. Matrix.prototype.invertToRef = function (other) {
  4114. var l1 = this.m[0];
  4115. var l2 = this.m[1];
  4116. var l3 = this.m[2];
  4117. var l4 = this.m[3];
  4118. var l5 = this.m[4];
  4119. var l6 = this.m[5];
  4120. var l7 = this.m[6];
  4121. var l8 = this.m[7];
  4122. var l9 = this.m[8];
  4123. var l10 = this.m[9];
  4124. var l11 = this.m[10];
  4125. var l12 = this.m[11];
  4126. var l13 = this.m[12];
  4127. var l14 = this.m[13];
  4128. var l15 = this.m[14];
  4129. var l16 = this.m[15];
  4130. var l17 = (l11 * l16) - (l12 * l15);
  4131. var l18 = (l10 * l16) - (l12 * l14);
  4132. var l19 = (l10 * l15) - (l11 * l14);
  4133. var l20 = (l9 * l16) - (l12 * l13);
  4134. var l21 = (l9 * l15) - (l11 * l13);
  4135. var l22 = (l9 * l14) - (l10 * l13);
  4136. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  4137. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  4138. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  4139. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  4140. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  4141. var l28 = (l7 * l16) - (l8 * l15);
  4142. var l29 = (l6 * l16) - (l8 * l14);
  4143. var l30 = (l6 * l15) - (l7 * l14);
  4144. var l31 = (l5 * l16) - (l8 * l13);
  4145. var l32 = (l5 * l15) - (l7 * l13);
  4146. var l33 = (l5 * l14) - (l6 * l13);
  4147. var l34 = (l7 * l12) - (l8 * l11);
  4148. var l35 = (l6 * l12) - (l8 * l10);
  4149. var l36 = (l6 * l11) - (l7 * l10);
  4150. var l37 = (l5 * l12) - (l8 * l9);
  4151. var l38 = (l5 * l11) - (l7 * l9);
  4152. var l39 = (l5 * l10) - (l6 * l9);
  4153. other.m[0] = l23 * l27;
  4154. other.m[4] = l24 * l27;
  4155. other.m[8] = l25 * l27;
  4156. other.m[12] = l26 * l27;
  4157. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  4158. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  4159. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  4160. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  4161. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  4162. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  4163. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  4164. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  4165. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  4166. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  4167. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  4168. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  4169. other._markAsUpdated();
  4170. return this;
  4171. };
  4172. /**
  4173. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  4174. * Returns the updated Matrix.
  4175. */
  4176. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  4177. this.m[12] = x;
  4178. this.m[13] = y;
  4179. this.m[14] = z;
  4180. this._markAsUpdated();
  4181. return this;
  4182. };
  4183. /**
  4184. * Inserts the translation vector in the current Matrix.
  4185. * Returns the updated Matrix.
  4186. */
  4187. Matrix.prototype.setTranslation = function (vector3) {
  4188. this.m[12] = vector3.x;
  4189. this.m[13] = vector3.y;
  4190. this.m[14] = vector3.z;
  4191. this._markAsUpdated();
  4192. return this;
  4193. };
  4194. /**
  4195. * Returns a new Vector3 as the extracted translation from the Matrix.
  4196. */
  4197. Matrix.prototype.getTranslation = function () {
  4198. return new Vector3(this.m[12], this.m[13], this.m[14]);
  4199. };
  4200. /**
  4201. * Fill a Vector3 with the extracted translation from the Matrix.
  4202. */
  4203. Matrix.prototype.getTranslationToRef = function (result) {
  4204. result.x = this.m[12];
  4205. result.y = this.m[13];
  4206. result.z = this.m[14];
  4207. return this;
  4208. };
  4209. /**
  4210. * Remove rotation and scaling part from the Matrix.
  4211. * Returns the updated Matrix.
  4212. */
  4213. Matrix.prototype.removeRotationAndScaling = function () {
  4214. this.setRowFromFloats(0, 1, 0, 0, 0);
  4215. this.setRowFromFloats(1, 0, 1, 0, 0);
  4216. this.setRowFromFloats(2, 0, 0, 1, 0);
  4217. return this;
  4218. };
  4219. /**
  4220. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  4221. */
  4222. Matrix.prototype.multiply = function (other) {
  4223. var result = new Matrix();
  4224. this.multiplyToRef(other, result);
  4225. return result;
  4226. };
  4227. /**
  4228. * Updates the current Matrix from the passed one values.
  4229. * Returns the updated Matrix.
  4230. */
  4231. Matrix.prototype.copyFrom = function (other) {
  4232. for (var index = 0; index < 16; index++) {
  4233. this.m[index] = other.m[index];
  4234. }
  4235. this._markAsUpdated();
  4236. return this;
  4237. };
  4238. /**
  4239. * Populates the passed array from the starting index with the Matrix values.
  4240. * Returns the Matrix.
  4241. */
  4242. Matrix.prototype.copyToArray = function (array, offset) {
  4243. if (offset === void 0) { offset = 0; }
  4244. for (var index = 0; index < 16; index++) {
  4245. array[offset + index] = this.m[index];
  4246. }
  4247. return this;
  4248. };
  4249. /**
  4250. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  4251. */
  4252. Matrix.prototype.multiplyToRef = function (other, result) {
  4253. this.multiplyToArray(other, result.m, 0);
  4254. result._markAsUpdated();
  4255. return this;
  4256. };
  4257. /**
  4258. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  4259. */
  4260. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  4261. var tm0 = this.m[0];
  4262. var tm1 = this.m[1];
  4263. var tm2 = this.m[2];
  4264. var tm3 = this.m[3];
  4265. var tm4 = this.m[4];
  4266. var tm5 = this.m[5];
  4267. var tm6 = this.m[6];
  4268. var tm7 = this.m[7];
  4269. var tm8 = this.m[8];
  4270. var tm9 = this.m[9];
  4271. var tm10 = this.m[10];
  4272. var tm11 = this.m[11];
  4273. var tm12 = this.m[12];
  4274. var tm13 = this.m[13];
  4275. var tm14 = this.m[14];
  4276. var tm15 = this.m[15];
  4277. var om0 = other.m[0];
  4278. var om1 = other.m[1];
  4279. var om2 = other.m[2];
  4280. var om3 = other.m[3];
  4281. var om4 = other.m[4];
  4282. var om5 = other.m[5];
  4283. var om6 = other.m[6];
  4284. var om7 = other.m[7];
  4285. var om8 = other.m[8];
  4286. var om9 = other.m[9];
  4287. var om10 = other.m[10];
  4288. var om11 = other.m[11];
  4289. var om12 = other.m[12];
  4290. var om13 = other.m[13];
  4291. var om14 = other.m[14];
  4292. var om15 = other.m[15];
  4293. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  4294. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  4295. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  4296. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  4297. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  4298. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  4299. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  4300. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  4301. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  4302. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  4303. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  4304. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  4305. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  4306. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  4307. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  4308. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  4309. return this;
  4310. };
  4311. /**
  4312. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  4313. */
  4314. Matrix.prototype.equals = function (value) {
  4315. return value &&
  4316. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  4317. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  4318. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  4319. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  4320. };
  4321. /**
  4322. * Returns a new Matrix from the current Matrix.
  4323. */
  4324. Matrix.prototype.clone = function () {
  4325. 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]);
  4326. };
  4327. /**
  4328. * Returns the string "Matrix"
  4329. */
  4330. Matrix.prototype.getClassName = function () {
  4331. return "Matrix";
  4332. };
  4333. /**
  4334. * Returns the Matrix hash code.
  4335. */
  4336. Matrix.prototype.getHashCode = function () {
  4337. var hash = this.m[0] || 0;
  4338. for (var i = 1; i < 16; i++) {
  4339. hash = (hash * 397) ^ (this.m[i] || 0);
  4340. }
  4341. return hash;
  4342. };
  4343. /**
  4344. * Decomposes the current Matrix into :
  4345. * - a scale vector3 passed as a reference to update,
  4346. * - a rotation quaternion passed as a reference to update,
  4347. * - a translation vector3 passed as a reference to update.
  4348. * Returns the true if operation was successful.
  4349. */
  4350. Matrix.prototype.decompose = function (scale, rotation, translation) {
  4351. translation.x = this.m[12];
  4352. translation.y = this.m[13];
  4353. translation.z = this.m[14];
  4354. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  4355. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  4356. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  4357. if (this.determinant() <= 0) {
  4358. scale.y *= -1;
  4359. }
  4360. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  4361. rotation.x = 0;
  4362. rotation.y = 0;
  4363. rotation.z = 0;
  4364. rotation.w = 1;
  4365. return false;
  4366. }
  4367. 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]);
  4368. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  4369. return true;
  4370. };
  4371. /**
  4372. * Returns a new Matrix as the extracted rotation matrix from the current one.
  4373. */
  4374. Matrix.prototype.getRotationMatrix = function () {
  4375. var result = Matrix.Identity();
  4376. this.getRotationMatrixToRef(result);
  4377. return result;
  4378. };
  4379. /**
  4380. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  4381. * Returns the current Matrix.
  4382. */
  4383. Matrix.prototype.getRotationMatrixToRef = function (result) {
  4384. var m = this.m;
  4385. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  4386. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  4387. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  4388. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  4389. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  4390. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  4391. 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);
  4392. return this;
  4393. };
  4394. // Statics
  4395. /**
  4396. * Returns a new Matrix set from the starting index of the passed array.
  4397. */
  4398. Matrix.FromArray = function (array, offset) {
  4399. var result = new Matrix();
  4400. if (!offset) {
  4401. offset = 0;
  4402. }
  4403. Matrix.FromArrayToRef(array, offset, result);
  4404. return result;
  4405. };
  4406. /**
  4407. * Sets the passed "result" matrix from the starting index of the passed array.
  4408. */
  4409. Matrix.FromArrayToRef = function (array, offset, result) {
  4410. for (var index = 0; index < 16; index++) {
  4411. result.m[index] = array[index + offset];
  4412. }
  4413. result._markAsUpdated();
  4414. };
  4415. /**
  4416. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  4417. */
  4418. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  4419. for (var index = 0; index < 16; index++) {
  4420. result.m[index] = array[index + offset] * scale;
  4421. }
  4422. result._markAsUpdated();
  4423. };
  4424. /**
  4425. * Sets the passed matrix "result" with the 16 passed floats.
  4426. */
  4427. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  4428. result.m[0] = initialM11;
  4429. result.m[1] = initialM12;
  4430. result.m[2] = initialM13;
  4431. result.m[3] = initialM14;
  4432. result.m[4] = initialM21;
  4433. result.m[5] = initialM22;
  4434. result.m[6] = initialM23;
  4435. result.m[7] = initialM24;
  4436. result.m[8] = initialM31;
  4437. result.m[9] = initialM32;
  4438. result.m[10] = initialM33;
  4439. result.m[11] = initialM34;
  4440. result.m[12] = initialM41;
  4441. result.m[13] = initialM42;
  4442. result.m[14] = initialM43;
  4443. result.m[15] = initialM44;
  4444. result._markAsUpdated();
  4445. };
  4446. /**
  4447. * Returns the index-th row of the current matrix as a new Vector4.
  4448. */
  4449. Matrix.prototype.getRow = function (index) {
  4450. if (index < 0 || index > 3) {
  4451. return null;
  4452. }
  4453. var i = index * 4;
  4454. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  4455. };
  4456. /**
  4457. * Sets the index-th row of the current matrix with the passed Vector4 values.
  4458. * Returns the updated Matrix.
  4459. */
  4460. Matrix.prototype.setRow = function (index, row) {
  4461. if (index < 0 || index > 3) {
  4462. return this;
  4463. }
  4464. var i = index * 4;
  4465. this.m[i + 0] = row.x;
  4466. this.m[i + 1] = row.y;
  4467. this.m[i + 2] = row.z;
  4468. this.m[i + 3] = row.w;
  4469. this._markAsUpdated();
  4470. return this;
  4471. };
  4472. /**
  4473. * Compute the transpose of the matrix.
  4474. * Returns a new Matrix.
  4475. */
  4476. Matrix.prototype.transpose = function () {
  4477. return Matrix.Transpose(this);
  4478. };
  4479. /**
  4480. * Compute the transpose of the matrix.
  4481. * Returns the current matrix.
  4482. */
  4483. Matrix.prototype.transposeToRef = function (result) {
  4484. Matrix.TransposeToRef(this, result);
  4485. return this;
  4486. };
  4487. /**
  4488. * Sets the index-th row of the current matrix with the passed 4 x float values.
  4489. * Returns the updated Matrix.
  4490. */
  4491. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  4492. if (index < 0 || index > 3) {
  4493. return this;
  4494. }
  4495. var i = index * 4;
  4496. this.m[i + 0] = x;
  4497. this.m[i + 1] = y;
  4498. this.m[i + 2] = z;
  4499. this.m[i + 3] = w;
  4500. this._markAsUpdated();
  4501. return this;
  4502. };
  4503. Object.defineProperty(Matrix, "IdentityReadOnly", {
  4504. /**
  4505. * Static identity matrix to be used as readonly matrix
  4506. * Must not be updated.
  4507. */
  4508. get: function () {
  4509. return Matrix._identityReadOnly;
  4510. },
  4511. enumerable: true,
  4512. configurable: true
  4513. });
  4514. /**
  4515. * Returns a new Matrix set from the 16 passed floats.
  4516. */
  4517. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  4518. var result = new Matrix();
  4519. result.m[0] = initialM11;
  4520. result.m[1] = initialM12;
  4521. result.m[2] = initialM13;
  4522. result.m[3] = initialM14;
  4523. result.m[4] = initialM21;
  4524. result.m[5] = initialM22;
  4525. result.m[6] = initialM23;
  4526. result.m[7] = initialM24;
  4527. result.m[8] = initialM31;
  4528. result.m[9] = initialM32;
  4529. result.m[10] = initialM33;
  4530. result.m[11] = initialM34;
  4531. result.m[12] = initialM41;
  4532. result.m[13] = initialM42;
  4533. result.m[14] = initialM43;
  4534. result.m[15] = initialM44;
  4535. return result;
  4536. };
  4537. /**
  4538. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  4539. */
  4540. Matrix.Compose = function (scale, rotation, translation) {
  4541. var result = Matrix.Identity();
  4542. Matrix.ComposeToRef(scale, rotation, translation, result);
  4543. return result;
  4544. };
  4545. /**
  4546. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  4547. */
  4548. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  4549. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  4550. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  4551. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  4552. result.setTranslation(translation);
  4553. };
  4554. /**
  4555. * Returns a new indentity Matrix.
  4556. */
  4557. Matrix.Identity = function () {
  4558. 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);
  4559. };
  4560. /**
  4561. * Sets the passed "result" as an identity matrix.
  4562. */
  4563. Matrix.IdentityToRef = function (result) {
  4564. 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);
  4565. };
  4566. /**
  4567. * Returns a new zero Matrix.
  4568. */
  4569. Matrix.Zero = function () {
  4570. 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);
  4571. };
  4572. /**
  4573. * Returns a new rotation matrix for "angle" radians around the X axis.
  4574. */
  4575. Matrix.RotationX = function (angle) {
  4576. var result = new Matrix();
  4577. Matrix.RotationXToRef(angle, result);
  4578. return result;
  4579. };
  4580. /**
  4581. * Returns a new Matrix as the passed inverted one.
  4582. */
  4583. Matrix.Invert = function (source) {
  4584. var result = new Matrix();
  4585. source.invertToRef(result);
  4586. return result;
  4587. };
  4588. /**
  4589. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  4590. */
  4591. Matrix.RotationXToRef = function (angle, result) {
  4592. var s = Math.sin(angle);
  4593. var c = Math.cos(angle);
  4594. result.m[0] = 1.0;
  4595. result.m[15] = 1.0;
  4596. result.m[5] = c;
  4597. result.m[10] = c;
  4598. result.m[9] = -s;
  4599. result.m[6] = s;
  4600. result.m[1] = 0.0;
  4601. result.m[2] = 0.0;
  4602. result.m[3] = 0.0;
  4603. result.m[4] = 0.0;
  4604. result.m[7] = 0.0;
  4605. result.m[8] = 0.0;
  4606. result.m[11] = 0.0;
  4607. result.m[12] = 0.0;
  4608. result.m[13] = 0.0;
  4609. result.m[14] = 0.0;
  4610. result._markAsUpdated();
  4611. };
  4612. /**
  4613. * Returns a new rotation matrix for "angle" radians around the Y axis.
  4614. */
  4615. Matrix.RotationY = function (angle) {
  4616. var result = new Matrix();
  4617. Matrix.RotationYToRef(angle, result);
  4618. return result;
  4619. };
  4620. /**
  4621. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  4622. */
  4623. Matrix.RotationYToRef = function (angle, result) {
  4624. var s = Math.sin(angle);
  4625. var c = Math.cos(angle);
  4626. result.m[5] = 1.0;
  4627. result.m[15] = 1.0;
  4628. result.m[0] = c;
  4629. result.m[2] = -s;
  4630. result.m[8] = s;
  4631. result.m[10] = c;
  4632. result.m[1] = 0.0;
  4633. result.m[3] = 0.0;
  4634. result.m[4] = 0.0;
  4635. result.m[6] = 0.0;
  4636. result.m[7] = 0.0;
  4637. result.m[9] = 0.0;
  4638. result.m[11] = 0.0;
  4639. result.m[12] = 0.0;
  4640. result.m[13] = 0.0;
  4641. result.m[14] = 0.0;
  4642. result._markAsUpdated();
  4643. };
  4644. /**
  4645. * Returns a new rotation matrix for "angle" radians around the Z axis.
  4646. */
  4647. Matrix.RotationZ = function (angle) {
  4648. var result = new Matrix();
  4649. Matrix.RotationZToRef(angle, result);
  4650. return result;
  4651. };
  4652. /**
  4653. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  4654. */
  4655. Matrix.RotationZToRef = function (angle, result) {
  4656. var s = Math.sin(angle);
  4657. var c = Math.cos(angle);
  4658. result.m[10] = 1.0;
  4659. result.m[15] = 1.0;
  4660. result.m[0] = c;
  4661. result.m[1] = s;
  4662. result.m[4] = -s;
  4663. result.m[5] = c;
  4664. result.m[2] = 0.0;
  4665. result.m[3] = 0.0;
  4666. result.m[6] = 0.0;
  4667. result.m[7] = 0.0;
  4668. result.m[8] = 0.0;
  4669. result.m[9] = 0.0;
  4670. result.m[11] = 0.0;
  4671. result.m[12] = 0.0;
  4672. result.m[13] = 0.0;
  4673. result.m[14] = 0.0;
  4674. result._markAsUpdated();
  4675. };
  4676. /**
  4677. * Returns a new rotation matrix for "angle" radians around the passed axis.
  4678. */
  4679. Matrix.RotationAxis = function (axis, angle) {
  4680. var result = Matrix.Zero();
  4681. Matrix.RotationAxisToRef(axis, angle, result);
  4682. return result;
  4683. };
  4684. /**
  4685. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  4686. */
  4687. Matrix.RotationAxisToRef = function (axis, angle, result) {
  4688. var s = Math.sin(-angle);
  4689. var c = Math.cos(-angle);
  4690. var c1 = 1 - c;
  4691. axis.normalize();
  4692. result.m[0] = (axis.x * axis.x) * c1 + c;
  4693. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  4694. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  4695. result.m[3] = 0.0;
  4696. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  4697. result.m[5] = (axis.y * axis.y) * c1 + c;
  4698. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  4699. result.m[7] = 0.0;
  4700. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  4701. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  4702. result.m[10] = (axis.z * axis.z) * c1 + c;
  4703. result.m[11] = 0.0;
  4704. result.m[15] = 1.0;
  4705. result._markAsUpdated();
  4706. };
  4707. /**
  4708. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  4709. */
  4710. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4711. var result = new Matrix();
  4712. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  4713. return result;
  4714. };
  4715. /**
  4716. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  4717. */
  4718. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4719. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  4720. this._tempQuaternion.toRotationMatrix(result);
  4721. };
  4722. /**
  4723. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  4724. */
  4725. Matrix.Scaling = function (x, y, z) {
  4726. var result = Matrix.Zero();
  4727. Matrix.ScalingToRef(x, y, z, result);
  4728. return result;
  4729. };
  4730. /**
  4731. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  4732. */
  4733. Matrix.ScalingToRef = function (x, y, z, result) {
  4734. result.m[0] = x;
  4735. result.m[1] = 0.0;
  4736. result.m[2] = 0.0;
  4737. result.m[3] = 0.0;
  4738. result.m[4] = 0.0;
  4739. result.m[5] = y;
  4740. result.m[6] = 0.0;
  4741. result.m[7] = 0.0;
  4742. result.m[8] = 0.0;
  4743. result.m[9] = 0.0;
  4744. result.m[10] = z;
  4745. result.m[11] = 0.0;
  4746. result.m[12] = 0.0;
  4747. result.m[13] = 0.0;
  4748. result.m[14] = 0.0;
  4749. result.m[15] = 1.0;
  4750. result._markAsUpdated();
  4751. };
  4752. /**
  4753. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  4754. */
  4755. Matrix.Translation = function (x, y, z) {
  4756. var result = Matrix.Identity();
  4757. Matrix.TranslationToRef(x, y, z, result);
  4758. return result;
  4759. };
  4760. /**
  4761. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  4762. */
  4763. Matrix.TranslationToRef = function (x, y, z, result) {
  4764. 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);
  4765. };
  4766. /**
  4767. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  4768. */
  4769. Matrix.Lerp = function (startValue, endValue, gradient) {
  4770. var result = Matrix.Zero();
  4771. for (var index = 0; index < 16; index++) {
  4772. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  4773. }
  4774. result._markAsUpdated();
  4775. return result;
  4776. };
  4777. /**
  4778. * Returns a new Matrix whose values are computed by :
  4779. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  4780. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  4781. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  4782. */
  4783. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  4784. var startScale = new Vector3(0, 0, 0);
  4785. var startRotation = new Quaternion();
  4786. var startTranslation = new Vector3(0, 0, 0);
  4787. startValue.decompose(startScale, startRotation, startTranslation);
  4788. var endScale = new Vector3(0, 0, 0);
  4789. var endRotation = new Quaternion();
  4790. var endTranslation = new Vector3(0, 0, 0);
  4791. endValue.decompose(endScale, endRotation, endTranslation);
  4792. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  4793. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  4794. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  4795. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  4796. };
  4797. /**
  4798. * 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".
  4799. * This methods works for a Left-Handed system.
  4800. */
  4801. Matrix.LookAtLH = function (eye, target, up) {
  4802. var result = Matrix.Zero();
  4803. Matrix.LookAtLHToRef(eye, target, up, result);
  4804. return result;
  4805. };
  4806. /**
  4807. * 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".
  4808. * This methods works for a Left-Handed system.
  4809. */
  4810. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  4811. // Z axis
  4812. target.subtractToRef(eye, this._zAxis);
  4813. this._zAxis.normalize();
  4814. // X axis
  4815. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  4816. if (this._xAxis.lengthSquared() === 0) {
  4817. this._xAxis.x = 1.0;
  4818. }
  4819. else {
  4820. this._xAxis.normalize();
  4821. }
  4822. // Y axis
  4823. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  4824. this._yAxis.normalize();
  4825. // Eye angles
  4826. var ex = -Vector3.Dot(this._xAxis, eye);
  4827. var ey = -Vector3.Dot(this._yAxis, eye);
  4828. var ez = -Vector3.Dot(this._zAxis, eye);
  4829. 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);
  4830. };
  4831. /**
  4832. * 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".
  4833. * This methods works for a Right-Handed system.
  4834. */
  4835. Matrix.LookAtRH = function (eye, target, up) {
  4836. var result = Matrix.Zero();
  4837. Matrix.LookAtRHToRef(eye, target, up, result);
  4838. return result;
  4839. };
  4840. /**
  4841. * 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".
  4842. * This methods works for a Left-Handed system.
  4843. */
  4844. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  4845. // Z axis
  4846. eye.subtractToRef(target, this._zAxis);
  4847. this._zAxis.normalize();
  4848. // X axis
  4849. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  4850. if (this._xAxis.lengthSquared() === 0) {
  4851. this._xAxis.x = 1.0;
  4852. }
  4853. else {
  4854. this._xAxis.normalize();
  4855. }
  4856. // Y axis
  4857. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  4858. this._yAxis.normalize();
  4859. // Eye angles
  4860. var ex = -Vector3.Dot(this._xAxis, eye);
  4861. var ey = -Vector3.Dot(this._yAxis, eye);
  4862. var ez = -Vector3.Dot(this._zAxis, eye);
  4863. 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);
  4864. };
  4865. /**
  4866. * 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.
  4867. */
  4868. Matrix.OrthoLH = function (width, height, znear, zfar) {
  4869. var matrix = Matrix.Zero();
  4870. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  4871. return matrix;
  4872. };
  4873. /**
  4874. * 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.
  4875. */
  4876. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  4877. var n = znear;
  4878. var f = zfar;
  4879. var a = 2.0 / width;
  4880. var b = 2.0 / height;
  4881. var c = 2.0 / (f - n);
  4882. var d = -(f + n) / (f - n);
  4883. 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);
  4884. };
  4885. /**
  4886. * 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.
  4887. */
  4888. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  4889. var matrix = Matrix.Zero();
  4890. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  4891. return matrix;
  4892. };
  4893. /**
  4894. * 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.
  4895. */
  4896. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  4897. var n = znear;
  4898. var f = zfar;
  4899. var a = 2.0 / (right - left);
  4900. var b = 2.0 / (top - bottom);
  4901. var c = 2.0 / (f - n);
  4902. var d = -(f + n) / (f - n);
  4903. var i0 = (left + right) / (left - right);
  4904. var i1 = (top + bottom) / (bottom - top);
  4905. 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);
  4906. };
  4907. /**
  4908. * 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.
  4909. */
  4910. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  4911. var matrix = Matrix.Zero();
  4912. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  4913. return matrix;
  4914. };
  4915. /**
  4916. * 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.
  4917. */
  4918. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  4919. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  4920. result.m[10] *= -1.0;
  4921. };
  4922. /**
  4923. * 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.
  4924. */
  4925. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  4926. var matrix = Matrix.Zero();
  4927. var n = znear;
  4928. var f = zfar;
  4929. var a = 2.0 * n / width;
  4930. var b = 2.0 * n / height;
  4931. var c = (f + n) / (f - n);
  4932. var d = -2.0 * f * n / (f - n);
  4933. 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);
  4934. return matrix;
  4935. };
  4936. /**
  4937. * 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.
  4938. */
  4939. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  4940. var matrix = Matrix.Zero();
  4941. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  4942. return matrix;
  4943. };
  4944. /**
  4945. * 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.
  4946. */
  4947. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  4948. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  4949. var n = znear;
  4950. var f = zfar;
  4951. var t = 1.0 / (Math.tan(fov * 0.5));
  4952. var a = isVerticalFovFixed ? (t / aspect) : t;
  4953. var b = isVerticalFovFixed ? t : (t * aspect);
  4954. var c = (f + n) / (f - n);
  4955. var d = -2.0 * f * n / (f - n);
  4956. 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);
  4957. };
  4958. /**
  4959. * 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.
  4960. */
  4961. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  4962. var matrix = Matrix.Zero();
  4963. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  4964. return matrix;
  4965. };
  4966. /**
  4967. * 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.
  4968. */
  4969. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  4970. //alternatively this could be expressed as:
  4971. // m = PerspectiveFovLHToRef
  4972. // m[10] *= -1.0;
  4973. // m[11] *= -1.0;
  4974. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  4975. var n = znear;
  4976. var f = zfar;
  4977. var t = 1.0 / (Math.tan(fov * 0.5));
  4978. var a = isVerticalFovFixed ? (t / aspect) : t;
  4979. var b = isVerticalFovFixed ? t : (t * aspect);
  4980. var c = -(f + n) / (f - n);
  4981. var d = -2 * f * n / (f - n);
  4982. 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);
  4983. };
  4984. /**
  4985. * 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.
  4986. */
  4987. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  4988. if (rightHanded === void 0) { rightHanded = false; }
  4989. var rightHandedFactor = rightHanded ? -1 : 1;
  4990. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  4991. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  4992. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  4993. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  4994. var xScale = 2.0 / (leftTan + rightTan);
  4995. var yScale = 2.0 / (upTan + downTan);
  4996. result.m[0] = xScale;
  4997. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  4998. result.m[5] = yScale;
  4999. result.m[6] = result.m[7] = 0.0;
  5000. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  5001. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  5002. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  5003. result.m[10] = -zfar / (znear - zfar);
  5004. result.m[11] = 1.0 * rightHandedFactor;
  5005. result.m[12] = result.m[13] = result.m[15] = 0.0;
  5006. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  5007. // result.m[14] = (znear * zfar) / (znear - zfar);
  5008. result._markAsUpdated();
  5009. };
  5010. /**
  5011. * Returns the final transformation matrix : world * view * projection * viewport
  5012. */
  5013. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5014. var cw = viewport.width;
  5015. var ch = viewport.height;
  5016. var cx = viewport.x;
  5017. var cy = viewport.y;
  5018. 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);
  5019. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5020. };
  5021. /**
  5022. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5023. */
  5024. Matrix.GetAsMatrix2x2 = function (matrix) {
  5025. return new Float32Array([
  5026. matrix.m[0], matrix.m[1],
  5027. matrix.m[4], matrix.m[5]
  5028. ]);
  5029. };
  5030. /**
  5031. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5032. */
  5033. Matrix.GetAsMatrix3x3 = function (matrix) {
  5034. return new Float32Array([
  5035. matrix.m[0], matrix.m[1], matrix.m[2],
  5036. matrix.m[4], matrix.m[5], matrix.m[6],
  5037. matrix.m[8], matrix.m[9], matrix.m[10]
  5038. ]);
  5039. };
  5040. /**
  5041. * Compute the transpose of the passed Matrix.
  5042. * Returns a new Matrix.
  5043. */
  5044. Matrix.Transpose = function (matrix) {
  5045. var result = new Matrix();
  5046. Matrix.TransposeToRef(matrix, result);
  5047. return result;
  5048. };
  5049. /**
  5050. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5051. */
  5052. Matrix.TransposeToRef = function (matrix, result) {
  5053. result.m[0] = matrix.m[0];
  5054. result.m[1] = matrix.m[4];
  5055. result.m[2] = matrix.m[8];
  5056. result.m[3] = matrix.m[12];
  5057. result.m[4] = matrix.m[1];
  5058. result.m[5] = matrix.m[5];
  5059. result.m[6] = matrix.m[9];
  5060. result.m[7] = matrix.m[13];
  5061. result.m[8] = matrix.m[2];
  5062. result.m[9] = matrix.m[6];
  5063. result.m[10] = matrix.m[10];
  5064. result.m[11] = matrix.m[14];
  5065. result.m[12] = matrix.m[3];
  5066. result.m[13] = matrix.m[7];
  5067. result.m[14] = matrix.m[11];
  5068. result.m[15] = matrix.m[15];
  5069. };
  5070. /**
  5071. * Returns a new Matrix as the reflection matrix across the passed plane.
  5072. */
  5073. Matrix.Reflection = function (plane) {
  5074. var matrix = new Matrix();
  5075. Matrix.ReflectionToRef(plane, matrix);
  5076. return matrix;
  5077. };
  5078. /**
  5079. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  5080. */
  5081. Matrix.ReflectionToRef = function (plane, result) {
  5082. plane.normalize();
  5083. var x = plane.normal.x;
  5084. var y = plane.normal.y;
  5085. var z = plane.normal.z;
  5086. var temp = -2 * x;
  5087. var temp2 = -2 * y;
  5088. var temp3 = -2 * z;
  5089. result.m[0] = (temp * x) + 1;
  5090. result.m[1] = temp2 * x;
  5091. result.m[2] = temp3 * x;
  5092. result.m[3] = 0.0;
  5093. result.m[4] = temp * y;
  5094. result.m[5] = (temp2 * y) + 1;
  5095. result.m[6] = temp3 * y;
  5096. result.m[7] = 0.0;
  5097. result.m[8] = temp * z;
  5098. result.m[9] = temp2 * z;
  5099. result.m[10] = (temp3 * z) + 1;
  5100. result.m[11] = 0.0;
  5101. result.m[12] = temp * plane.d;
  5102. result.m[13] = temp2 * plane.d;
  5103. result.m[14] = temp3 * plane.d;
  5104. result.m[15] = 1.0;
  5105. result._markAsUpdated();
  5106. };
  5107. /**
  5108. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  5109. */
  5110. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  5111. result.m[0] = xaxis.x;
  5112. result.m[1] = xaxis.y;
  5113. result.m[2] = xaxis.z;
  5114. result.m[3] = 0.0;
  5115. result.m[4] = yaxis.x;
  5116. result.m[5] = yaxis.y;
  5117. result.m[6] = yaxis.z;
  5118. result.m[7] = 0.0;
  5119. result.m[8] = zaxis.x;
  5120. result.m[9] = zaxis.y;
  5121. result.m[10] = zaxis.z;
  5122. result.m[11] = 0.0;
  5123. result.m[12] = 0.0;
  5124. result.m[13] = 0.0;
  5125. result.m[14] = 0.0;
  5126. result.m[15] = 1.0;
  5127. result._markAsUpdated();
  5128. };
  5129. /**
  5130. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  5131. */
  5132. Matrix.FromQuaternionToRef = function (quat, result) {
  5133. var xx = quat.x * quat.x;
  5134. var yy = quat.y * quat.y;
  5135. var zz = quat.z * quat.z;
  5136. var xy = quat.x * quat.y;
  5137. var zw = quat.z * quat.w;
  5138. var zx = quat.z * quat.x;
  5139. var yw = quat.y * quat.w;
  5140. var yz = quat.y * quat.z;
  5141. var xw = quat.x * quat.w;
  5142. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5143. result.m[1] = 2.0 * (xy + zw);
  5144. result.m[2] = 2.0 * (zx - yw);
  5145. result.m[3] = 0.0;
  5146. result.m[4] = 2.0 * (xy - zw);
  5147. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5148. result.m[6] = 2.0 * (yz + xw);
  5149. result.m[7] = 0.0;
  5150. result.m[8] = 2.0 * (zx + yw);
  5151. result.m[9] = 2.0 * (yz - xw);
  5152. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5153. result.m[11] = 0.0;
  5154. result.m[12] = 0.0;
  5155. result.m[13] = 0.0;
  5156. result.m[14] = 0.0;
  5157. result.m[15] = 1.0;
  5158. result._markAsUpdated();
  5159. };
  5160. Matrix._tempQuaternion = new Quaternion();
  5161. Matrix._xAxis = Vector3.Zero();
  5162. Matrix._yAxis = Vector3.Zero();
  5163. Matrix._zAxis = Vector3.Zero();
  5164. Matrix._updateFlagSeed = 0;
  5165. Matrix._identityReadOnly = Matrix.Identity();
  5166. return Matrix;
  5167. }());
  5168. BABYLON.Matrix = Matrix;
  5169. var Plane = /** @class */ (function () {
  5170. /**
  5171. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  5172. */
  5173. function Plane(a, b, c, d) {
  5174. this.normal = new Vector3(a, b, c);
  5175. this.d = d;
  5176. }
  5177. /**
  5178. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  5179. */
  5180. Plane.prototype.asArray = function () {
  5181. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  5182. };
  5183. // Methods
  5184. /**
  5185. * Returns a new plane copied from the current Plane.
  5186. */
  5187. Plane.prototype.clone = function () {
  5188. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  5189. };
  5190. /**
  5191. * Returns the string "Plane".
  5192. */
  5193. Plane.prototype.getClassName = function () {
  5194. return "Plane";
  5195. };
  5196. /**
  5197. * Returns the Plane hash code.
  5198. */
  5199. Plane.prototype.getHashCode = function () {
  5200. var hash = this.normal.getHashCode();
  5201. hash = (hash * 397) ^ (this.d || 0);
  5202. return hash;
  5203. };
  5204. /**
  5205. * Normalize the current Plane in place.
  5206. * Returns the updated Plane.
  5207. */
  5208. Plane.prototype.normalize = function () {
  5209. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  5210. var magnitude = 0.0;
  5211. if (norm !== 0) {
  5212. magnitude = 1.0 / norm;
  5213. }
  5214. this.normal.x *= magnitude;
  5215. this.normal.y *= magnitude;
  5216. this.normal.z *= magnitude;
  5217. this.d *= magnitude;
  5218. return this;
  5219. };
  5220. /**
  5221. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  5222. */
  5223. Plane.prototype.transform = function (transformation) {
  5224. var transposedMatrix = Matrix.Transpose(transformation);
  5225. var x = this.normal.x;
  5226. var y = this.normal.y;
  5227. var z = this.normal.z;
  5228. var d = this.d;
  5229. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  5230. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  5231. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  5232. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  5233. return new Plane(normalX, normalY, normalZ, finalD);
  5234. };
  5235. /**
  5236. * Returns the dot product (float) of the point coordinates and the plane normal.
  5237. */
  5238. Plane.prototype.dotCoordinate = function (point) {
  5239. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  5240. };
  5241. /**
  5242. * Updates the current Plane from the plane defined by the three passed points.
  5243. * Returns the updated Plane.
  5244. */
  5245. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  5246. var x1 = point2.x - point1.x;
  5247. var y1 = point2.y - point1.y;
  5248. var z1 = point2.z - point1.z;
  5249. var x2 = point3.x - point1.x;
  5250. var y2 = point3.y - point1.y;
  5251. var z2 = point3.z - point1.z;
  5252. var yz = (y1 * z2) - (z1 * y2);
  5253. var xz = (z1 * x2) - (x1 * z2);
  5254. var xy = (x1 * y2) - (y1 * x2);
  5255. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  5256. var invPyth;
  5257. if (pyth !== 0) {
  5258. invPyth = 1.0 / pyth;
  5259. }
  5260. else {
  5261. invPyth = 0.0;
  5262. }
  5263. this.normal.x = yz * invPyth;
  5264. this.normal.y = xz * invPyth;
  5265. this.normal.z = xy * invPyth;
  5266. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  5267. return this;
  5268. };
  5269. /**
  5270. * Boolean : True is the vector "direction" is the same side than the plane normal.
  5271. */
  5272. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  5273. var dot = Vector3.Dot(this.normal, direction);
  5274. return (dot <= epsilon);
  5275. };
  5276. /**
  5277. * Returns the signed distance (float) from the passed point to the Plane.
  5278. */
  5279. Plane.prototype.signedDistanceTo = function (point) {
  5280. return Vector3.Dot(point, this.normal) + this.d;
  5281. };
  5282. // Statics
  5283. /**
  5284. * Returns a new Plane from the passed array.
  5285. */
  5286. Plane.FromArray = function (array) {
  5287. return new Plane(array[0], array[1], array[2], array[3]);
  5288. };
  5289. /**
  5290. * Returns a new Plane defined by the three passed points.
  5291. */
  5292. Plane.FromPoints = function (point1, point2, point3) {
  5293. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5294. result.copyFromPoints(point1, point2, point3);
  5295. return result;
  5296. };
  5297. /**
  5298. * Returns a new Plane the normal vector to this plane at the passed origin point.
  5299. * Note : the vector "normal" is updated because normalized.
  5300. */
  5301. Plane.FromPositionAndNormal = function (origin, normal) {
  5302. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5303. normal.normalize();
  5304. result.normal = normal;
  5305. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5306. return result;
  5307. };
  5308. /**
  5309. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  5310. */
  5311. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  5312. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5313. return Vector3.Dot(point, normal) + d;
  5314. };
  5315. return Plane;
  5316. }());
  5317. BABYLON.Plane = Plane;
  5318. var Viewport = /** @class */ (function () {
  5319. /**
  5320. * Creates a Viewport object located at (x, y) and sized (width, height).
  5321. */
  5322. function Viewport(x, y, width, height) {
  5323. this.x = x;
  5324. this.y = y;
  5325. this.width = width;
  5326. this.height = height;
  5327. }
  5328. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  5329. if (renderWidthOrEngine.getRenderWidth) {
  5330. var engine = renderWidthOrEngine;
  5331. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  5332. }
  5333. var renderWidth = renderWidthOrEngine;
  5334. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  5335. };
  5336. /**
  5337. * Returns a new Viewport copied from the current one.
  5338. */
  5339. Viewport.prototype.clone = function () {
  5340. return new Viewport(this.x, this.y, this.width, this.height);
  5341. };
  5342. return Viewport;
  5343. }());
  5344. BABYLON.Viewport = Viewport;
  5345. var Frustum = /** @class */ (function () {
  5346. function Frustum() {
  5347. }
  5348. /**
  5349. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  5350. */
  5351. Frustum.GetPlanes = function (transform) {
  5352. var frustumPlanes = [];
  5353. for (var index = 0; index < 6; index++) {
  5354. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  5355. }
  5356. Frustum.GetPlanesToRef(transform, frustumPlanes);
  5357. return frustumPlanes;
  5358. };
  5359. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  5360. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  5361. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  5362. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  5363. frustumPlane.d = transform.m[15] + transform.m[14];
  5364. frustumPlane.normalize();
  5365. };
  5366. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  5367. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  5368. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  5369. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  5370. frustumPlane.d = transform.m[15] - transform.m[14];
  5371. frustumPlane.normalize();
  5372. };
  5373. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  5374. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  5375. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  5376. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  5377. frustumPlane.d = transform.m[15] + transform.m[12];
  5378. frustumPlane.normalize();
  5379. };
  5380. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  5381. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  5382. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  5383. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  5384. frustumPlane.d = transform.m[15] - transform.m[12];
  5385. frustumPlane.normalize();
  5386. };
  5387. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  5388. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  5389. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  5390. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  5391. frustumPlane.d = transform.m[15] - transform.m[13];
  5392. frustumPlane.normalize();
  5393. };
  5394. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  5395. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  5396. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  5397. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  5398. frustumPlane.d = transform.m[15] + transform.m[13];
  5399. frustumPlane.normalize();
  5400. };
  5401. /**
  5402. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  5403. */
  5404. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  5405. // Near
  5406. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  5407. // Far
  5408. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  5409. // Left
  5410. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  5411. // Right
  5412. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  5413. // Top
  5414. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  5415. // Bottom
  5416. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  5417. };
  5418. return Frustum;
  5419. }());
  5420. BABYLON.Frustum = Frustum;
  5421. var Space;
  5422. (function (Space) {
  5423. Space[Space["LOCAL"] = 0] = "LOCAL";
  5424. Space[Space["WORLD"] = 1] = "WORLD";
  5425. Space[Space["BONE"] = 2] = "BONE";
  5426. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  5427. var Axis = /** @class */ (function () {
  5428. function Axis() {
  5429. }
  5430. Axis.X = new Vector3(1.0, 0.0, 0.0);
  5431. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  5432. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  5433. return Axis;
  5434. }());
  5435. BABYLON.Axis = Axis;
  5436. ;
  5437. var BezierCurve = /** @class */ (function () {
  5438. function BezierCurve() {
  5439. }
  5440. /**
  5441. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  5442. */
  5443. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  5444. // Extract X (which is equal to time here)
  5445. var f0 = 1 - 3 * x2 + 3 * x1;
  5446. var f1 = 3 * x2 - 6 * x1;
  5447. var f2 = 3 * x1;
  5448. var refinedT = t;
  5449. for (var i = 0; i < 5; i++) {
  5450. var refinedT2 = refinedT * refinedT;
  5451. var refinedT3 = refinedT2 * refinedT;
  5452. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  5453. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  5454. refinedT -= (x - t) * slope;
  5455. refinedT = Math.min(1, Math.max(0, refinedT));
  5456. }
  5457. // Resolve cubic bezier for the given x
  5458. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  5459. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  5460. Math.pow(refinedT, 3);
  5461. };
  5462. return BezierCurve;
  5463. }());
  5464. BABYLON.BezierCurve = BezierCurve;
  5465. var Orientation;
  5466. (function (Orientation) {
  5467. Orientation[Orientation["CW"] = 0] = "CW";
  5468. Orientation[Orientation["CCW"] = 1] = "CCW";
  5469. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  5470. var Angle = /** @class */ (function () {
  5471. /**
  5472. * Creates an Angle object of "radians" radians (float).
  5473. */
  5474. function Angle(radians) {
  5475. var _this = this;
  5476. /**
  5477. * Returns the Angle value in degrees (float).
  5478. */
  5479. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  5480. /**
  5481. * Returns the Angle value in radians (float).
  5482. */
  5483. this.radians = function () { return _this._radians; };
  5484. this._radians = radians;
  5485. if (this._radians < 0.0)
  5486. this._radians += (2.0 * Math.PI);
  5487. }
  5488. /**
  5489. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  5490. */
  5491. Angle.BetweenTwoPoints = function (a, b) {
  5492. var delta = b.subtract(a);
  5493. var theta = Math.atan2(delta.y, delta.x);
  5494. return new Angle(theta);
  5495. };
  5496. /**
  5497. * Returns a new Angle object from the passed float in radians.
  5498. */
  5499. Angle.FromRadians = function (radians) {
  5500. return new Angle(radians);
  5501. };
  5502. /**
  5503. * Returns a new Angle object from the passed float in degrees.
  5504. */
  5505. Angle.FromDegrees = function (degrees) {
  5506. return new Angle(degrees * Math.PI / 180.0);
  5507. };
  5508. return Angle;
  5509. }());
  5510. BABYLON.Angle = Angle;
  5511. var Arc2 = /** @class */ (function () {
  5512. /**
  5513. * Creates an Arc object from the three passed points : start, middle and end.
  5514. */
  5515. function Arc2(startPoint, midPoint, endPoint) {
  5516. this.startPoint = startPoint;
  5517. this.midPoint = midPoint;
  5518. this.endPoint = endPoint;
  5519. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  5520. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  5521. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  5522. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  5523. 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);
  5524. this.radius = this.centerPoint.subtract(this.startPoint).length();
  5525. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  5526. var a1 = this.startAngle.degrees();
  5527. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  5528. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  5529. // angles correction
  5530. if (a2 - a1 > +180.0)
  5531. a2 -= 360.0;
  5532. if (a2 - a1 < -180.0)
  5533. a2 += 360.0;
  5534. if (a3 - a2 > +180.0)
  5535. a3 -= 360.0;
  5536. if (a3 - a2 < -180.0)
  5537. a3 += 360.0;
  5538. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  5539. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  5540. }
  5541. return Arc2;
  5542. }());
  5543. BABYLON.Arc2 = Arc2;
  5544. var Path2 = /** @class */ (function () {
  5545. /**
  5546. * Creates a Path2 object from the starting 2D coordinates x and y.
  5547. */
  5548. function Path2(x, y) {
  5549. this._points = new Array();
  5550. this._length = 0.0;
  5551. this.closed = false;
  5552. this._points.push(new Vector2(x, y));
  5553. }
  5554. /**
  5555. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  5556. * Returns the updated Path2.
  5557. */
  5558. Path2.prototype.addLineTo = function (x, y) {
  5559. if (this.closed) {
  5560. //Tools.Error("cannot add lines to closed paths");
  5561. return this;
  5562. }
  5563. var newPoint = new Vector2(x, y);
  5564. var previousPoint = this._points[this._points.length - 1];
  5565. this._points.push(newPoint);
  5566. this._length += newPoint.subtract(previousPoint).length();
  5567. return this;
  5568. };
  5569. /**
  5570. * 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.
  5571. * Returns the updated Path2.
  5572. */
  5573. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  5574. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  5575. if (this.closed) {
  5576. //Tools.Error("cannot add arcs to closed paths");
  5577. return this;
  5578. }
  5579. var startPoint = this._points[this._points.length - 1];
  5580. var midPoint = new Vector2(midX, midY);
  5581. var endPoint = new Vector2(endX, endY);
  5582. var arc = new Arc2(startPoint, midPoint, endPoint);
  5583. var increment = arc.angle.radians() / numberOfSegments;
  5584. if (arc.orientation === Orientation.CW)
  5585. increment *= -1;
  5586. var currentAngle = arc.startAngle.radians() + increment;
  5587. for (var i = 0; i < numberOfSegments; i++) {
  5588. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  5589. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  5590. this.addLineTo(x, y);
  5591. currentAngle += increment;
  5592. }
  5593. return this;
  5594. };
  5595. /**
  5596. * Closes the Path2.
  5597. * Returns the Path2.
  5598. */
  5599. Path2.prototype.close = function () {
  5600. this.closed = true;
  5601. return this;
  5602. };
  5603. /**
  5604. * Returns the Path2 total length (float).
  5605. */
  5606. Path2.prototype.length = function () {
  5607. var result = this._length;
  5608. if (!this.closed) {
  5609. var lastPoint = this._points[this._points.length - 1];
  5610. var firstPoint = this._points[0];
  5611. result += (firstPoint.subtract(lastPoint).length());
  5612. }
  5613. return result;
  5614. };
  5615. /**
  5616. * Returns the Path2 internal array of points.
  5617. */
  5618. Path2.prototype.getPoints = function () {
  5619. return this._points;
  5620. };
  5621. /**
  5622. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  5623. */
  5624. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  5625. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  5626. //Tools.Error("normalized length position should be between 0 and 1.");
  5627. return Vector2.Zero();
  5628. }
  5629. var lengthPosition = normalizedLengthPosition * this.length();
  5630. var previousOffset = 0;
  5631. for (var i = 0; i < this._points.length; i++) {
  5632. var j = (i + 1) % this._points.length;
  5633. var a = this._points[i];
  5634. var b = this._points[j];
  5635. var bToA = b.subtract(a);
  5636. var nextOffset = (bToA.length() + previousOffset);
  5637. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  5638. var dir = bToA.normalize();
  5639. var localOffset = lengthPosition - previousOffset;
  5640. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  5641. }
  5642. previousOffset = nextOffset;
  5643. }
  5644. //Tools.Error("internal error");
  5645. return Vector2.Zero();
  5646. };
  5647. /**
  5648. * Returns a new Path2 starting at the coordinates (x, y).
  5649. */
  5650. Path2.StartingAt = function (x, y) {
  5651. return new Path2(x, y);
  5652. };
  5653. return Path2;
  5654. }());
  5655. BABYLON.Path2 = Path2;
  5656. var Path3D = /** @class */ (function () {
  5657. /**
  5658. * new Path3D(path, normal, raw)
  5659. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  5660. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  5661. * path : an array of Vector3, the curve axis of the Path3D
  5662. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  5663. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  5664. */
  5665. function Path3D(path, firstNormal, raw) {
  5666. if (firstNormal === void 0) { firstNormal = null; }
  5667. this.path = path;
  5668. this._curve = new Array();
  5669. this._distances = new Array();
  5670. this._tangents = new Array();
  5671. this._normals = new Array();
  5672. this._binormals = new Array();
  5673. for (var p = 0; p < path.length; p++) {
  5674. this._curve[p] = path[p].clone(); // hard copy
  5675. }
  5676. this._raw = raw || false;
  5677. this._compute(firstNormal);
  5678. }
  5679. /**
  5680. * Returns the Path3D array of successive Vector3 designing its curve.
  5681. */
  5682. Path3D.prototype.getCurve = function () {
  5683. return this._curve;
  5684. };
  5685. /**
  5686. * Returns an array populated with tangent vectors on each Path3D curve point.
  5687. */
  5688. Path3D.prototype.getTangents = function () {
  5689. return this._tangents;
  5690. };
  5691. /**
  5692. * Returns an array populated with normal vectors on each Path3D curve point.
  5693. */
  5694. Path3D.prototype.getNormals = function () {
  5695. return this._normals;
  5696. };
  5697. /**
  5698. * Returns an array populated with binormal vectors on each Path3D curve point.
  5699. */
  5700. Path3D.prototype.getBinormals = function () {
  5701. return this._binormals;
  5702. };
  5703. /**
  5704. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  5705. */
  5706. Path3D.prototype.getDistances = function () {
  5707. return this._distances;
  5708. };
  5709. /**
  5710. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  5711. * Returns the same object updated.
  5712. */
  5713. Path3D.prototype.update = function (path, firstNormal) {
  5714. if (firstNormal === void 0) { firstNormal = null; }
  5715. for (var p = 0; p < path.length; p++) {
  5716. this._curve[p].x = path[p].x;
  5717. this._curve[p].y = path[p].y;
  5718. this._curve[p].z = path[p].z;
  5719. }
  5720. this._compute(firstNormal);
  5721. return this;
  5722. };
  5723. // private function compute() : computes tangents, normals and binormals
  5724. Path3D.prototype._compute = function (firstNormal) {
  5725. var l = this._curve.length;
  5726. // first and last tangents
  5727. this._tangents[0] = this._getFirstNonNullVector(0);
  5728. if (!this._raw) {
  5729. this._tangents[0].normalize();
  5730. }
  5731. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  5732. if (!this._raw) {
  5733. this._tangents[l - 1].normalize();
  5734. }
  5735. // normals and binormals at first point : arbitrary vector with _normalVector()
  5736. var tg0 = this._tangents[0];
  5737. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  5738. this._normals[0] = pp0;
  5739. if (!this._raw) {
  5740. this._normals[0].normalize();
  5741. }
  5742. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  5743. if (!this._raw) {
  5744. this._binormals[0].normalize();
  5745. }
  5746. this._distances[0] = 0.0;
  5747. // normals and binormals : next points
  5748. var prev; // previous vector (segment)
  5749. var cur; // current vector (segment)
  5750. var curTang; // current tangent
  5751. // previous normal
  5752. var prevBinor; // previous binormal
  5753. for (var i = 1; i < l; i++) {
  5754. // tangents
  5755. prev = this._getLastNonNullVector(i);
  5756. if (i < l - 1) {
  5757. cur = this._getFirstNonNullVector(i);
  5758. this._tangents[i] = prev.add(cur);
  5759. this._tangents[i].normalize();
  5760. }
  5761. this._distances[i] = this._distances[i - 1] + prev.length();
  5762. // normals and binormals
  5763. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  5764. curTang = this._tangents[i];
  5765. prevBinor = this._binormals[i - 1];
  5766. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  5767. if (!this._raw) {
  5768. this._normals[i].normalize();
  5769. }
  5770. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  5771. if (!this._raw) {
  5772. this._binormals[i].normalize();
  5773. }
  5774. }
  5775. };
  5776. // private function getFirstNonNullVector(index)
  5777. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  5778. Path3D.prototype._getFirstNonNullVector = function (index) {
  5779. var i = 1;
  5780. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  5781. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  5782. i++;
  5783. nNVector = this._curve[index + i].subtract(this._curve[index]);
  5784. }
  5785. return nNVector;
  5786. };
  5787. // private function getLastNonNullVector(index)
  5788. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  5789. Path3D.prototype._getLastNonNullVector = function (index) {
  5790. var i = 1;
  5791. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  5792. while (nLVector.length() === 0 && index > i + 1) {
  5793. i++;
  5794. nLVector = this._curve[index].subtract(this._curve[index - i]);
  5795. }
  5796. return nLVector;
  5797. };
  5798. // private function normalVector(v0, vt, va) :
  5799. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  5800. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  5801. Path3D.prototype._normalVector = function (v0, vt, va) {
  5802. var normal0;
  5803. var tgl = vt.length();
  5804. if (tgl === 0.0) {
  5805. tgl = 1.0;
  5806. }
  5807. if (va === undefined || va === null) {
  5808. var point;
  5809. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  5810. point = new Vector3(0.0, -1.0, 0.0);
  5811. }
  5812. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  5813. point = new Vector3(1.0, 0.0, 0.0);
  5814. }
  5815. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  5816. point = new Vector3(0.0, 0.0, 1.0);
  5817. }
  5818. else {
  5819. point = Vector3.Zero();
  5820. }
  5821. normal0 = Vector3.Cross(vt, point);
  5822. }
  5823. else {
  5824. normal0 = Vector3.Cross(vt, va);
  5825. Vector3.CrossToRef(normal0, vt, normal0);
  5826. }
  5827. normal0.normalize();
  5828. return normal0;
  5829. };
  5830. return Path3D;
  5831. }());
  5832. BABYLON.Path3D = Path3D;
  5833. var Curve3 = /** @class */ (function () {
  5834. /**
  5835. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  5836. * A Curve3 is designed from a series of successive Vector3.
  5837. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  5838. */
  5839. function Curve3(points) {
  5840. this._length = 0.0;
  5841. this._points = points;
  5842. this._length = this._computeLength(points);
  5843. }
  5844. /**
  5845. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  5846. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  5847. * @param v1 (Vector3) the control point
  5848. * @param v2 (Vector3) the end point of the Quadratic Bezier
  5849. * @param nbPoints (integer) the wanted number of points in the curve
  5850. */
  5851. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  5852. nbPoints = nbPoints > 2 ? nbPoints : 3;
  5853. var bez = new Array();
  5854. var equation = function (t, val0, val1, val2) {
  5855. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  5856. return res;
  5857. };
  5858. for (var i = 0; i <= nbPoints; i++) {
  5859. 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)));
  5860. }
  5861. return new Curve3(bez);
  5862. };
  5863. /**
  5864. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  5865. * @param v0 (Vector3) the origin point of the Cubic Bezier
  5866. * @param v1 (Vector3) the first control point
  5867. * @param v2 (Vector3) the second control point
  5868. * @param v3 (Vector3) the end point of the Cubic Bezier
  5869. * @param nbPoints (integer) the wanted number of points in the curve
  5870. */
  5871. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  5872. nbPoints = nbPoints > 3 ? nbPoints : 4;
  5873. var bez = new Array();
  5874. var equation = function (t, val0, val1, val2, val3) {
  5875. 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;
  5876. return res;
  5877. };
  5878. for (var i = 0; i <= nbPoints; i++) {
  5879. 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)));
  5880. }
  5881. return new Curve3(bez);
  5882. };
  5883. /**
  5884. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  5885. * @param p1 (Vector3) the origin point of the Hermite Spline
  5886. * @param t1 (Vector3) the tangent vector at the origin point
  5887. * @param p2 (Vector3) the end point of the Hermite Spline
  5888. * @param t2 (Vector3) the tangent vector at the end point
  5889. * @param nbPoints (integer) the wanted number of points in the curve
  5890. */
  5891. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  5892. var hermite = new Array();
  5893. var step = 1.0 / nbPoints;
  5894. for (var i = 0; i <= nbPoints; i++) {
  5895. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  5896. }
  5897. return new Curve3(hermite);
  5898. };
  5899. /**
  5900. * Returns a Curve3 object along a CatmullRom Spline curve :
  5901. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  5902. * @param nbPoints (integer) the wanted number of points between each curve control points.
  5903. */
  5904. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  5905. var totalPoints = new Array();
  5906. totalPoints.push(points[0].clone());
  5907. Array.prototype.push.apply(totalPoints, points);
  5908. totalPoints.push(points[points.length - 1].clone());
  5909. var catmullRom = new Array();
  5910. var step = 1.0 / nbPoints;
  5911. var amount = 0.0;
  5912. for (var i = 0; i < totalPoints.length - 3; i++) {
  5913. amount = 0;
  5914. for (var c = 0; c < nbPoints; c++) {
  5915. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  5916. amount += step;
  5917. }
  5918. }
  5919. i--;
  5920. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  5921. return new Curve3(catmullRom);
  5922. };
  5923. /**
  5924. * Returns the Curve3 stored array of successive Vector3
  5925. */
  5926. Curve3.prototype.getPoints = function () {
  5927. return this._points;
  5928. };
  5929. /**
  5930. * Returns the computed length (float) of the curve.
  5931. */
  5932. Curve3.prototype.length = function () {
  5933. return this._length;
  5934. };
  5935. /**
  5936. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  5937. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  5938. * curveA and curveB keep unchanged.
  5939. */
  5940. Curve3.prototype.continue = function (curve) {
  5941. var lastPoint = this._points[this._points.length - 1];
  5942. var continuedPoints = this._points.slice();
  5943. var curvePoints = curve.getPoints();
  5944. for (var i = 1; i < curvePoints.length; i++) {
  5945. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  5946. }
  5947. var continuedCurve = new Curve3(continuedPoints);
  5948. return continuedCurve;
  5949. };
  5950. Curve3.prototype._computeLength = function (path) {
  5951. var l = 0;
  5952. for (var i = 1; i < path.length; i++) {
  5953. l += (path[i].subtract(path[i - 1])).length();
  5954. }
  5955. return l;
  5956. };
  5957. return Curve3;
  5958. }());
  5959. BABYLON.Curve3 = Curve3;
  5960. // Vertex formats
  5961. var PositionNormalVertex = /** @class */ (function () {
  5962. function PositionNormalVertex(position, normal) {
  5963. if (position === void 0) { position = Vector3.Zero(); }
  5964. if (normal === void 0) { normal = Vector3.Up(); }
  5965. this.position = position;
  5966. this.normal = normal;
  5967. }
  5968. PositionNormalVertex.prototype.clone = function () {
  5969. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  5970. };
  5971. return PositionNormalVertex;
  5972. }());
  5973. BABYLON.PositionNormalVertex = PositionNormalVertex;
  5974. var PositionNormalTextureVertex = /** @class */ (function () {
  5975. function PositionNormalTextureVertex(position, normal, uv) {
  5976. if (position === void 0) { position = Vector3.Zero(); }
  5977. if (normal === void 0) { normal = Vector3.Up(); }
  5978. if (uv === void 0) { uv = Vector2.Zero(); }
  5979. this.position = position;
  5980. this.normal = normal;
  5981. this.uv = uv;
  5982. }
  5983. PositionNormalTextureVertex.prototype.clone = function () {
  5984. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  5985. };
  5986. return PositionNormalTextureVertex;
  5987. }());
  5988. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  5989. // Temporary pre-allocated objects for engine internal use
  5990. // usage in any internal function :
  5991. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  5992. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  5993. var Tmp = /** @class */ (function () {
  5994. function Tmp() {
  5995. }
  5996. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  5997. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  5998. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  5999. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  6000. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  6001. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  6002. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  6003. Matrix.Zero(), Matrix.Zero(),
  6004. Matrix.Zero(), Matrix.Zero(),
  6005. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  6006. return Tmp;
  6007. }());
  6008. BABYLON.Tmp = Tmp;
  6009. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  6010. var MathTmp = /** @class */ (function () {
  6011. function MathTmp() {
  6012. }
  6013. MathTmp.Vector3 = [Vector3.Zero()];
  6014. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6015. MathTmp.Quaternion = [Quaternion.Zero()];
  6016. return MathTmp;
  6017. }());
  6018. })(BABYLON || (BABYLON = {}));
  6019. //# sourceMappingURL=babylon.math.js.map
  6020. var BABYLON;
  6021. (function (BABYLON) {
  6022. var Scalar = /** @class */ (function () {
  6023. function Scalar() {
  6024. }
  6025. /**
  6026. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6027. */
  6028. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6029. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6030. var num = a - b;
  6031. return -epsilon <= num && num <= epsilon;
  6032. };
  6033. /**
  6034. * Returns a string : the upper case translation of the number i to hexadecimal.
  6035. */
  6036. Scalar.ToHex = function (i) {
  6037. var str = i.toString(16);
  6038. if (i <= 15) {
  6039. return ("0" + str).toUpperCase();
  6040. }
  6041. return str.toUpperCase();
  6042. };
  6043. /**
  6044. * Returns -1 if value is negative and +1 is value is positive.
  6045. * Returns the value itself if it's equal to zero.
  6046. */
  6047. Scalar.Sign = function (value) {
  6048. value = +value; // convert to a number
  6049. if (value === 0 || isNaN(value))
  6050. return value;
  6051. return value > 0 ? 1 : -1;
  6052. };
  6053. /**
  6054. * Returns the value itself if it's between min and max.
  6055. * Returns min if the value is lower than min.
  6056. * Returns max if the value is greater than max.
  6057. */
  6058. Scalar.Clamp = function (value, min, max) {
  6059. if (min === void 0) { min = 0; }
  6060. if (max === void 0) { max = 1; }
  6061. return Math.min(max, Math.max(min, value));
  6062. };
  6063. /**
  6064. * Returns the log2 of value.
  6065. */
  6066. Scalar.Log2 = function (value) {
  6067. return Math.log(value) * Math.LOG2E;
  6068. };
  6069. /**
  6070. * Loops the value, so that it is never larger than length and never smaller than 0.
  6071. *
  6072. * This is similar to the modulo operator but it works with floating point numbers.
  6073. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  6074. * With t = 5 and length = 2.5, the result would be 0.0.
  6075. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  6076. */
  6077. Scalar.Repeat = function (value, length) {
  6078. return value - Math.floor(value / length) * length;
  6079. };
  6080. /**
  6081. * Normalize the value between 0.0 and 1.0 using min and max values
  6082. */
  6083. Scalar.Normalize = function (value, min, max) {
  6084. return (value - min) / (max - min);
  6085. };
  6086. /**
  6087. * Denormalize the value from 0.0 and 1.0 using min and max values
  6088. */
  6089. Scalar.Denormalize = function (normalized, min, max) {
  6090. return (normalized * (max - min) + min);
  6091. };
  6092. /**
  6093. * Calculates the shortest difference between two given angles given in degrees.
  6094. */
  6095. Scalar.DeltaAngle = function (current, target) {
  6096. var num = Scalar.Repeat(target - current, 360.0);
  6097. if (num > 180.0) {
  6098. num -= 360.0;
  6099. }
  6100. return num;
  6101. };
  6102. /**
  6103. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  6104. *
  6105. * The returned value will move back and forth between 0 and length
  6106. */
  6107. Scalar.PingPong = function (tx, length) {
  6108. var t = Scalar.Repeat(tx, length * 2.0);
  6109. return length - Math.abs(t - length);
  6110. };
  6111. /**
  6112. * Interpolates between min and max with smoothing at the limits.
  6113. *
  6114. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  6115. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  6116. */
  6117. Scalar.SmoothStep = function (from, to, tx) {
  6118. var t = Scalar.Clamp(tx);
  6119. t = -2.0 * t * t * t + 3.0 * t * t;
  6120. return to * t + from * (1.0 - t);
  6121. };
  6122. /**
  6123. * Moves a value current towards target.
  6124. *
  6125. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  6126. * Negative values of maxDelta pushes the value away from target.
  6127. */
  6128. Scalar.MoveTowards = function (current, target, maxDelta) {
  6129. var result = 0;
  6130. if (Math.abs(target - current) <= maxDelta) {
  6131. result = target;
  6132. }
  6133. else {
  6134. result = current + Scalar.Sign(target - current) * maxDelta;
  6135. }
  6136. return result;
  6137. };
  6138. /**
  6139. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6140. *
  6141. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  6142. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  6143. */
  6144. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  6145. var num = Scalar.DeltaAngle(current, target);
  6146. var result = 0;
  6147. if (-maxDelta < num && num < maxDelta) {
  6148. result = target;
  6149. }
  6150. else {
  6151. target = current + num;
  6152. result = Scalar.MoveTowards(current, target, maxDelta);
  6153. }
  6154. return result;
  6155. };
  6156. /**
  6157. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  6158. */
  6159. Scalar.Lerp = function (start, end, amount) {
  6160. return start + ((end - start) * amount);
  6161. };
  6162. /**
  6163. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6164. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  6165. */
  6166. Scalar.LerpAngle = function (start, end, amount) {
  6167. var num = Scalar.Repeat(end - start, 360.0);
  6168. if (num > 180.0) {
  6169. num -= 360.0;
  6170. }
  6171. return start + num * Scalar.Clamp(amount);
  6172. };
  6173. /**
  6174. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  6175. */
  6176. Scalar.InverseLerp = function (a, b, value) {
  6177. var result = 0;
  6178. if (a != b) {
  6179. result = Scalar.Clamp((value - a) / (b - a));
  6180. }
  6181. else {
  6182. result = 0.0;
  6183. }
  6184. return result;
  6185. };
  6186. /**
  6187. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  6188. */
  6189. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  6190. var squared = amount * amount;
  6191. var cubed = amount * squared;
  6192. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  6193. var part2 = (-2.0 * cubed) + (3.0 * squared);
  6194. var part3 = (cubed - (2.0 * squared)) + amount;
  6195. var part4 = cubed - squared;
  6196. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  6197. };
  6198. /**
  6199. * Returns a random float number between and min and max values
  6200. */
  6201. Scalar.RandomRange = function (min, max) {
  6202. if (min === max)
  6203. return min;
  6204. return ((Math.random() * (max - min)) + min);
  6205. };
  6206. /**
  6207. * This function returns percentage of a number in a given range.
  6208. *
  6209. * RangeToPercent(40,20,60) will return 0.5 (50%)
  6210. * RangeToPercent(34,0,100) will return 0.34 (34%)
  6211. */
  6212. Scalar.RangeToPercent = function (number, min, max) {
  6213. return ((number - min) / (max - min));
  6214. };
  6215. /**
  6216. * This function returns number that corresponds to the percentage in a given range.
  6217. *
  6218. * PercentToRange(0.34,0,100) will return 34.
  6219. */
  6220. Scalar.PercentToRange = function (percent, min, max) {
  6221. return ((max - min) * percent + min);
  6222. };
  6223. /**
  6224. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  6225. * @param angle The angle to normalize in radian.
  6226. * @return The converted angle.
  6227. */
  6228. Scalar.NormalizeRadians = function (angle) {
  6229. // More precise but slower version kept for reference.
  6230. // angle = angle % Tools.TwoPi;
  6231. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  6232. //if (angle > Math.PI) {
  6233. // angle -= Tools.TwoPi;
  6234. //}
  6235. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  6236. return angle;
  6237. };
  6238. /**
  6239. * Two pi constants convenient for computation.
  6240. */
  6241. Scalar.TwoPi = Math.PI * 2;
  6242. return Scalar;
  6243. }());
  6244. BABYLON.Scalar = Scalar;
  6245. })(BABYLON || (BABYLON = {}));
  6246. //# sourceMappingURL=babylon.math.scalar.js.map
  6247. //# sourceMappingURL=babylon.mixins.js.map
  6248. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  6249. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  6250. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  6251. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  6252. //# sourceMappingURL=babylon.webgl2.js.map
  6253. var BABYLON;
  6254. (function (BABYLON) {
  6255. var __decoratorInitialStore = {};
  6256. var __mergedStore = {};
  6257. var _copySource = function (creationFunction, source, instanciate) {
  6258. var destination = creationFunction();
  6259. // Tags
  6260. if (BABYLON.Tags) {
  6261. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6262. }
  6263. var classStore = getMergedStore(destination);
  6264. // Properties
  6265. for (var property in classStore) {
  6266. var propertyDescriptor = classStore[property];
  6267. var sourceProperty = source[property];
  6268. var propertyType = propertyDescriptor.type;
  6269. if (sourceProperty !== undefined && sourceProperty !== null) {
  6270. switch (propertyType) {
  6271. case 0: // Value
  6272. case 6:// Mesh reference
  6273. destination[property] = sourceProperty;
  6274. break;
  6275. case 1:// Texture
  6276. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  6277. break;
  6278. case 2: // Color3
  6279. case 3: // FresnelParameters
  6280. case 4: // Vector2
  6281. case 5: // Vector3
  6282. case 7: // Color Curves
  6283. case 10:// Quaternion
  6284. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  6285. break;
  6286. }
  6287. }
  6288. }
  6289. return destination;
  6290. };
  6291. function getDirectStore(target) {
  6292. var classKey = target.getClassName();
  6293. if (!__decoratorInitialStore[classKey]) {
  6294. __decoratorInitialStore[classKey] = {};
  6295. }
  6296. return __decoratorInitialStore[classKey];
  6297. }
  6298. /**
  6299. * Return the list of properties flagged as serializable
  6300. * @param target: host object
  6301. */
  6302. function getMergedStore(target) {
  6303. var classKey = target.getClassName();
  6304. if (__mergedStore[classKey]) {
  6305. return __mergedStore[classKey];
  6306. }
  6307. __mergedStore[classKey] = {};
  6308. var store = __mergedStore[classKey];
  6309. var currentTarget = target;
  6310. var currentKey = classKey;
  6311. while (currentKey) {
  6312. var initialStore = __decoratorInitialStore[currentKey];
  6313. for (var property in initialStore) {
  6314. store[property] = initialStore[property];
  6315. }
  6316. var parent_1 = void 0;
  6317. var done = false;
  6318. do {
  6319. parent_1 = Object.getPrototypeOf(currentTarget);
  6320. if (!parent_1.getClassName) {
  6321. done = true;
  6322. break;
  6323. }
  6324. if (parent_1.getClassName() !== currentKey) {
  6325. break;
  6326. }
  6327. currentTarget = parent_1;
  6328. } while (parent_1);
  6329. if (done) {
  6330. break;
  6331. }
  6332. currentKey = parent_1.getClassName();
  6333. currentTarget = parent_1;
  6334. }
  6335. return store;
  6336. }
  6337. function generateSerializableMember(type, sourceName) {
  6338. return function (target, propertyKey) {
  6339. var classStore = getDirectStore(target);
  6340. if (!classStore[propertyKey]) {
  6341. classStore[propertyKey] = { type: type, sourceName: sourceName };
  6342. }
  6343. };
  6344. }
  6345. function generateExpandMember(setCallback, targetKey) {
  6346. if (targetKey === void 0) { targetKey = null; }
  6347. return function (target, propertyKey) {
  6348. var key = targetKey || ("_" + propertyKey);
  6349. Object.defineProperty(target, propertyKey, {
  6350. get: function () {
  6351. return this[key];
  6352. },
  6353. set: function (value) {
  6354. if (this[key] === value) {
  6355. return;
  6356. }
  6357. this[key] = value;
  6358. target[setCallback].apply(this);
  6359. },
  6360. enumerable: true,
  6361. configurable: true
  6362. });
  6363. };
  6364. }
  6365. function expandToProperty(callback, targetKey) {
  6366. if (targetKey === void 0) { targetKey = null; }
  6367. return generateExpandMember(callback, targetKey);
  6368. }
  6369. BABYLON.expandToProperty = expandToProperty;
  6370. function serialize(sourceName) {
  6371. return generateSerializableMember(0, sourceName); // value member
  6372. }
  6373. BABYLON.serialize = serialize;
  6374. function serializeAsTexture(sourceName) {
  6375. return generateSerializableMember(1, sourceName); // texture member
  6376. }
  6377. BABYLON.serializeAsTexture = serializeAsTexture;
  6378. function serializeAsColor3(sourceName) {
  6379. return generateSerializableMember(2, sourceName); // color3 member
  6380. }
  6381. BABYLON.serializeAsColor3 = serializeAsColor3;
  6382. function serializeAsFresnelParameters(sourceName) {
  6383. return generateSerializableMember(3, sourceName); // fresnel parameters member
  6384. }
  6385. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  6386. function serializeAsVector2(sourceName) {
  6387. return generateSerializableMember(4, sourceName); // vector2 member
  6388. }
  6389. BABYLON.serializeAsVector2 = serializeAsVector2;
  6390. function serializeAsVector3(sourceName) {
  6391. return generateSerializableMember(5, sourceName); // vector3 member
  6392. }
  6393. BABYLON.serializeAsVector3 = serializeAsVector3;
  6394. function serializeAsMeshReference(sourceName) {
  6395. return generateSerializableMember(6, sourceName); // mesh reference member
  6396. }
  6397. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  6398. function serializeAsColorCurves(sourceName) {
  6399. return generateSerializableMember(7, sourceName); // color curves
  6400. }
  6401. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  6402. function serializeAsColor4(sourceName) {
  6403. return generateSerializableMember(8, sourceName); // color 4
  6404. }
  6405. BABYLON.serializeAsColor4 = serializeAsColor4;
  6406. function serializeAsImageProcessingConfiguration(sourceName) {
  6407. return generateSerializableMember(9, sourceName); // image processing
  6408. }
  6409. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  6410. function serializeAsQuaternion(sourceName) {
  6411. return generateSerializableMember(10, sourceName); // quaternion member
  6412. }
  6413. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  6414. var SerializationHelper = /** @class */ (function () {
  6415. function SerializationHelper() {
  6416. }
  6417. SerializationHelper.Serialize = function (entity, serializationObject) {
  6418. if (!serializationObject) {
  6419. serializationObject = {};
  6420. }
  6421. // Tags
  6422. if (BABYLON.Tags) {
  6423. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  6424. }
  6425. var serializedProperties = getMergedStore(entity);
  6426. // Properties
  6427. for (var property in serializedProperties) {
  6428. var propertyDescriptor = serializedProperties[property];
  6429. var targetPropertyName = propertyDescriptor.sourceName || property;
  6430. var propertyType = propertyDescriptor.type;
  6431. var sourceProperty = entity[property];
  6432. if (sourceProperty !== undefined && sourceProperty !== null) {
  6433. switch (propertyType) {
  6434. case 0:// Value
  6435. serializationObject[targetPropertyName] = sourceProperty;
  6436. break;
  6437. case 1:// Texture
  6438. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6439. break;
  6440. case 2:// Color3
  6441. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6442. break;
  6443. case 3:// FresnelParameters
  6444. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6445. break;
  6446. case 4:// Vector2
  6447. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6448. break;
  6449. case 5:// Vector3
  6450. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6451. break;
  6452. case 6:// Mesh reference
  6453. serializationObject[targetPropertyName] = sourceProperty.id;
  6454. break;
  6455. case 7:// Color Curves
  6456. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6457. break;
  6458. case 8:// Color 4
  6459. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6460. break;
  6461. case 9:// Image Processing
  6462. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6463. break;
  6464. }
  6465. }
  6466. }
  6467. return serializationObject;
  6468. };
  6469. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  6470. if (rootUrl === void 0) { rootUrl = null; }
  6471. var destination = creationFunction();
  6472. if (!rootUrl) {
  6473. rootUrl = "";
  6474. }
  6475. // Tags
  6476. if (BABYLON.Tags) {
  6477. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6478. }
  6479. var classStore = getMergedStore(destination);
  6480. // Properties
  6481. for (var property in classStore) {
  6482. var propertyDescriptor = classStore[property];
  6483. var sourceProperty = source[propertyDescriptor.sourceName || property];
  6484. var propertyType = propertyDescriptor.type;
  6485. if (sourceProperty !== undefined && sourceProperty !== null) {
  6486. var dest = destination;
  6487. switch (propertyType) {
  6488. case 0:// Value
  6489. dest[property] = sourceProperty;
  6490. break;
  6491. case 1:// Texture
  6492. if (scene) {
  6493. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  6494. }
  6495. break;
  6496. case 2:// Color3
  6497. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  6498. break;
  6499. case 3:// FresnelParameters
  6500. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  6501. break;
  6502. case 4:// Vector2
  6503. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  6504. break;
  6505. case 5:// Vector3
  6506. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  6507. break;
  6508. case 6:// Mesh reference
  6509. if (scene) {
  6510. dest[property] = scene.getLastMeshByID(sourceProperty);
  6511. }
  6512. break;
  6513. case 7:// Color Curves
  6514. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  6515. break;
  6516. case 8:// Color 4
  6517. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  6518. break;
  6519. case 9:// Image Processing
  6520. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  6521. break;
  6522. }
  6523. }
  6524. }
  6525. return destination;
  6526. };
  6527. SerializationHelper.Clone = function (creationFunction, source) {
  6528. return _copySource(creationFunction, source, false);
  6529. };
  6530. SerializationHelper.Instanciate = function (creationFunction, source) {
  6531. return _copySource(creationFunction, source, true);
  6532. };
  6533. return SerializationHelper;
  6534. }());
  6535. BABYLON.SerializationHelper = SerializationHelper;
  6536. })(BABYLON || (BABYLON = {}));
  6537. //# sourceMappingURL=babylon.decorators.js.map
  6538. var BABYLON;
  6539. (function (BABYLON) {
  6540. /**
  6541. * A class serves as a medium between the observable and its observers
  6542. */
  6543. var EventState = /** @class */ (function () {
  6544. /**
  6545. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  6546. */
  6547. function EventState(mask, skipNextObservers, target, currentTarget) {
  6548. if (skipNextObservers === void 0) { skipNextObservers = false; }
  6549. this.initalize(mask, skipNextObservers, target, currentTarget);
  6550. }
  6551. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  6552. if (skipNextObservers === void 0) { skipNextObservers = false; }
  6553. this.mask = mask;
  6554. this.skipNextObservers = skipNextObservers;
  6555. this.target = target;
  6556. this.currentTarget = currentTarget;
  6557. return this;
  6558. };
  6559. return EventState;
  6560. }());
  6561. BABYLON.EventState = EventState;
  6562. /**
  6563. * Represent an Observer registered to a given Observable object.
  6564. */
  6565. var Observer = /** @class */ (function () {
  6566. function Observer(callback, mask, scope) {
  6567. if (scope === void 0) { scope = null; }
  6568. this.callback = callback;
  6569. this.mask = mask;
  6570. this.scope = scope;
  6571. }
  6572. return Observer;
  6573. }());
  6574. BABYLON.Observer = Observer;
  6575. /**
  6576. * Represent a list of observers registered to multiple Observables object.
  6577. */
  6578. var MultiObserver = /** @class */ (function () {
  6579. function MultiObserver() {
  6580. }
  6581. MultiObserver.prototype.dispose = function () {
  6582. if (this._observers && this._observables) {
  6583. for (var index = 0; index < this._observers.length; index++) {
  6584. this._observables[index].remove(this._observers[index]);
  6585. }
  6586. }
  6587. this._observers = null;
  6588. this._observables = null;
  6589. };
  6590. MultiObserver.Watch = function (observables, callback, mask, scope) {
  6591. if (mask === void 0) { mask = -1; }
  6592. if (scope === void 0) { scope = null; }
  6593. var result = new MultiObserver();
  6594. result._observers = new Array();
  6595. result._observables = observables;
  6596. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  6597. var observable = observables_1[_i];
  6598. var observer = observable.add(callback, mask, false, scope);
  6599. if (observer) {
  6600. result._observers.push(observer);
  6601. }
  6602. }
  6603. return result;
  6604. };
  6605. return MultiObserver;
  6606. }());
  6607. BABYLON.MultiObserver = MultiObserver;
  6608. /**
  6609. * The Observable class is a simple implementation of the Observable pattern.
  6610. * 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.
  6611. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  6612. * 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).
  6613. * 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.
  6614. */
  6615. var Observable = /** @class */ (function () {
  6616. function Observable(onObserverAdded) {
  6617. this._observers = new Array();
  6618. this._eventState = new EventState(0);
  6619. if (onObserverAdded) {
  6620. this._onObserverAdded = onObserverAdded;
  6621. }
  6622. }
  6623. /**
  6624. * Create a new Observer with the specified callback
  6625. * @param callback the callback that will be executed for that Observer
  6626. * @param mask the mask used to filter observers
  6627. * @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.
  6628. * @param scope optional scope for the callback to be called from
  6629. */
  6630. Observable.prototype.add = function (callback, mask, insertFirst, scope) {
  6631. if (mask === void 0) { mask = -1; }
  6632. if (insertFirst === void 0) { insertFirst = false; }
  6633. if (scope === void 0) { scope = null; }
  6634. if (!callback) {
  6635. return null;
  6636. }
  6637. var observer = new Observer(callback, mask, scope);
  6638. if (insertFirst) {
  6639. this._observers.unshift(observer);
  6640. }
  6641. else {
  6642. this._observers.push(observer);
  6643. }
  6644. if (this._onObserverAdded) {
  6645. this._onObserverAdded(observer);
  6646. }
  6647. return observer;
  6648. };
  6649. /**
  6650. * Remove an Observer from the Observable object
  6651. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  6652. */
  6653. Observable.prototype.remove = function (observer) {
  6654. if (!observer) {
  6655. return false;
  6656. }
  6657. var index = this._observers.indexOf(observer);
  6658. if (index !== -1) {
  6659. this._observers.splice(index, 1);
  6660. return true;
  6661. }
  6662. return false;
  6663. };
  6664. /**
  6665. * Remove a callback from the Observable object
  6666. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  6667. * @param scope optional scope. If used only the callbacks with this scope will be removed.
  6668. */
  6669. Observable.prototype.removeCallback = function (callback, scope) {
  6670. for (var index = 0; index < this._observers.length; index++) {
  6671. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  6672. this._observers.splice(index, 1);
  6673. return true;
  6674. }
  6675. }
  6676. return false;
  6677. };
  6678. /**
  6679. * Notify all Observers by calling their respective callback with the given data
  6680. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  6681. * @param eventData
  6682. * @param mask
  6683. */
  6684. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  6685. if (mask === void 0) { mask = -1; }
  6686. if (!this._observers.length) {
  6687. return true;
  6688. }
  6689. var state = this._eventState;
  6690. state.mask = mask;
  6691. state.target = target;
  6692. state.currentTarget = currentTarget;
  6693. state.skipNextObservers = false;
  6694. state.lastReturnValue = eventData;
  6695. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  6696. var obs = _a[_i];
  6697. if (obs.mask & mask) {
  6698. if (obs.scope) {
  6699. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  6700. }
  6701. else {
  6702. state.lastReturnValue = obs.callback(eventData, state);
  6703. }
  6704. }
  6705. if (state.skipNextObservers) {
  6706. return false;
  6707. }
  6708. }
  6709. return true;
  6710. };
  6711. /**
  6712. * Calling this will execute each callback, expecting it to be a promise or return a value.
  6713. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  6714. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  6715. * and it is crucial that all callbacks will be executed.
  6716. * The order of the callbacks is kept, callbacks are not executed parallel.
  6717. *
  6718. * @param eventData The data to be sent to each callback
  6719. * @param mask is used to filter observers defaults to -1
  6720. * @param target the callback target (see EventState)
  6721. * @param currentTarget The current object in the bubbling phase
  6722. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  6723. */
  6724. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  6725. if (mask === void 0) { mask = -1; }
  6726. // create an empty promise
  6727. var p = Promise.resolve(eventData);
  6728. // no observers? return this promise.
  6729. if (!this._observers.length) {
  6730. return p;
  6731. }
  6732. var state = this._eventState;
  6733. state.mask = mask;
  6734. state.target = target;
  6735. state.currentTarget = currentTarget;
  6736. state.skipNextObservers = false;
  6737. // execute one callback after another (not using Promise.all, the order is important)
  6738. this._observers.forEach(function (obs) {
  6739. if (state.skipNextObservers) {
  6740. return;
  6741. }
  6742. if (obs.mask & mask) {
  6743. if (obs.scope) {
  6744. p = p.then(function (lastReturnedValue) {
  6745. state.lastReturnValue = lastReturnedValue;
  6746. return obs.callback.apply(obs.scope, [eventData, state]);
  6747. });
  6748. }
  6749. else {
  6750. p = p.then(function (lastReturnedValue) {
  6751. state.lastReturnValue = lastReturnedValue;
  6752. return obs.callback(eventData, state);
  6753. });
  6754. }
  6755. }
  6756. });
  6757. // return the eventData
  6758. return p.then(function () { return eventData; });
  6759. };
  6760. /**
  6761. * Notify a specific observer
  6762. * @param eventData
  6763. * @param mask
  6764. */
  6765. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  6766. if (mask === void 0) { mask = -1; }
  6767. var state = this._eventState;
  6768. state.mask = mask;
  6769. state.skipNextObservers = false;
  6770. observer.callback(eventData, state);
  6771. };
  6772. /**
  6773. * return true is the Observable has at least one Observer registered
  6774. */
  6775. Observable.prototype.hasObservers = function () {
  6776. return this._observers.length > 0;
  6777. };
  6778. /**
  6779. * Clear the list of observers
  6780. */
  6781. Observable.prototype.clear = function () {
  6782. this._observers = new Array();
  6783. this._onObserverAdded = null;
  6784. };
  6785. /**
  6786. * Clone the current observable
  6787. */
  6788. Observable.prototype.clone = function () {
  6789. var result = new Observable();
  6790. result._observers = this._observers.slice(0);
  6791. return result;
  6792. };
  6793. /**
  6794. * Does this observable handles observer registered with a given mask
  6795. * @param {number} trigger - the mask to be tested
  6796. * @return {boolean} whether or not one observer registered with the given mask is handeled
  6797. **/
  6798. Observable.prototype.hasSpecificMask = function (mask) {
  6799. if (mask === void 0) { mask = -1; }
  6800. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  6801. var obs = _a[_i];
  6802. if (obs.mask & mask || obs.mask === mask) {
  6803. return true;
  6804. }
  6805. }
  6806. return false;
  6807. };
  6808. return Observable;
  6809. }());
  6810. BABYLON.Observable = Observable;
  6811. })(BABYLON || (BABYLON = {}));
  6812. //# sourceMappingURL=babylon.observable.js.map
  6813. var BABYLON;
  6814. (function (BABYLON) {
  6815. var SmartArray = /** @class */ (function () {
  6816. function SmartArray(capacity) {
  6817. this.length = 0;
  6818. this.data = new Array(capacity);
  6819. this._id = SmartArray._GlobalId++;
  6820. }
  6821. SmartArray.prototype.push = function (value) {
  6822. this.data[this.length++] = value;
  6823. if (this.length > this.data.length) {
  6824. this.data.length *= 2;
  6825. }
  6826. };
  6827. SmartArray.prototype.forEach = function (func) {
  6828. for (var index = 0; index < this.length; index++) {
  6829. func(this.data[index]);
  6830. }
  6831. };
  6832. SmartArray.prototype.sort = function (compareFn) {
  6833. this.data.sort(compareFn);
  6834. };
  6835. SmartArray.prototype.reset = function () {
  6836. this.length = 0;
  6837. };
  6838. SmartArray.prototype.dispose = function () {
  6839. this.reset();
  6840. if (this.data) {
  6841. this.data.length = 0;
  6842. this.data = [];
  6843. }
  6844. };
  6845. SmartArray.prototype.concat = function (array) {
  6846. if (array.length === 0) {
  6847. return;
  6848. }
  6849. if (this.length + array.length > this.data.length) {
  6850. this.data.length = (this.length + array.length) * 2;
  6851. }
  6852. for (var index = 0; index < array.length; index++) {
  6853. this.data[this.length++] = (array.data || array)[index];
  6854. }
  6855. };
  6856. SmartArray.prototype.indexOf = function (value) {
  6857. var position = this.data.indexOf(value);
  6858. if (position >= this.length) {
  6859. return -1;
  6860. }
  6861. return position;
  6862. };
  6863. SmartArray.prototype.contains = function (value) {
  6864. return this.data.indexOf(value) !== -1;
  6865. };
  6866. // Statics
  6867. SmartArray._GlobalId = 0;
  6868. return SmartArray;
  6869. }());
  6870. BABYLON.SmartArray = SmartArray;
  6871. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  6872. __extends(SmartArrayNoDuplicate, _super);
  6873. function SmartArrayNoDuplicate() {
  6874. var _this = _super !== null && _super.apply(this, arguments) || this;
  6875. _this._duplicateId = 0;
  6876. return _this;
  6877. }
  6878. SmartArrayNoDuplicate.prototype.push = function (value) {
  6879. _super.prototype.push.call(this, value);
  6880. if (!value.__smartArrayFlags) {
  6881. value.__smartArrayFlags = {};
  6882. }
  6883. value.__smartArrayFlags[this._id] = this._duplicateId;
  6884. };
  6885. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  6886. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  6887. return false;
  6888. }
  6889. this.push(value);
  6890. return true;
  6891. };
  6892. SmartArrayNoDuplicate.prototype.reset = function () {
  6893. _super.prototype.reset.call(this);
  6894. this._duplicateId++;
  6895. };
  6896. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  6897. if (array.length === 0) {
  6898. return;
  6899. }
  6900. if (this.length + array.length > this.data.length) {
  6901. this.data.length = (this.length + array.length) * 2;
  6902. }
  6903. for (var index = 0; index < array.length; index++) {
  6904. var item = (array.data || array)[index];
  6905. this.pushNoDuplicate(item);
  6906. }
  6907. };
  6908. return SmartArrayNoDuplicate;
  6909. }(SmartArray));
  6910. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  6911. })(BABYLON || (BABYLON = {}));
  6912. //# sourceMappingURL=babylon.smartArray.js.map
  6913. var BABYLON;
  6914. (function (BABYLON) {
  6915. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  6916. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  6917. var LoadFileError = /** @class */ (function (_super) {
  6918. __extends(LoadFileError, _super);
  6919. function LoadFileError(message, request) {
  6920. var _this = _super.call(this, message) || this;
  6921. _this.request = request;
  6922. _this.name = "LoadFileError";
  6923. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  6924. return _this;
  6925. }
  6926. // Polyfill for Object.setPrototypeOf if necessary.
  6927. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  6928. return LoadFileError;
  6929. }(Error));
  6930. BABYLON.LoadFileError = LoadFileError;
  6931. var RetryStrategy = /** @class */ (function () {
  6932. function RetryStrategy() {
  6933. }
  6934. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  6935. if (maxRetries === void 0) { maxRetries = 3; }
  6936. if (baseInterval === void 0) { baseInterval = 500; }
  6937. return function (url, request, retryIndex) {
  6938. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  6939. return -1;
  6940. }
  6941. return Math.pow(2, retryIndex) * baseInterval;
  6942. };
  6943. };
  6944. return RetryStrategy;
  6945. }());
  6946. BABYLON.RetryStrategy = RetryStrategy;
  6947. // Screenshots
  6948. var screenshotCanvas;
  6949. var cloneValue = function (source, destinationObject) {
  6950. if (!source)
  6951. return null;
  6952. if (source instanceof BABYLON.Mesh) {
  6953. return null;
  6954. }
  6955. if (source instanceof BABYLON.SubMesh) {
  6956. return source.clone(destinationObject);
  6957. }
  6958. else if (source.clone) {
  6959. return source.clone();
  6960. }
  6961. return null;
  6962. };
  6963. var Tools = /** @class */ (function () {
  6964. function Tools() {
  6965. }
  6966. /**
  6967. * Interpolates between a and b via alpha
  6968. * @param a The lower value (returned when alpha = 0)
  6969. * @param b The upper value (returned when alpha = 1)
  6970. * @param alpha The interpolation-factor
  6971. * @return The mixed value
  6972. */
  6973. Tools.Mix = function (a, b, alpha) {
  6974. return a * (1 - alpha) + b * alpha;
  6975. };
  6976. Tools.Instantiate = function (className) {
  6977. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  6978. return Tools.RegisteredExternalClasses[className];
  6979. }
  6980. var arr = className.split(".");
  6981. var fn = (window || this);
  6982. for (var i = 0, len = arr.length; i < len; i++) {
  6983. fn = fn[arr[i]];
  6984. }
  6985. if (typeof fn !== "function") {
  6986. return null;
  6987. }
  6988. return fn;
  6989. };
  6990. /**
  6991. * Provides a slice function that will work even on IE
  6992. * @param data defines the array to slice
  6993. * @returns the new sliced array
  6994. */
  6995. Tools.Slice = function (data) {
  6996. if (data.slice) {
  6997. return data.slice();
  6998. }
  6999. return Array.prototype.slice.call(data);
  7000. };
  7001. Tools.SetImmediate = function (action) {
  7002. if (window.setImmediate) {
  7003. window.setImmediate(action);
  7004. }
  7005. else {
  7006. setTimeout(action, 1);
  7007. }
  7008. };
  7009. Tools.IsExponentOfTwo = function (value) {
  7010. var count = 1;
  7011. do {
  7012. count *= 2;
  7013. } while (count < value);
  7014. return count === value;
  7015. };
  7016. /**
  7017. * Find the next highest power of two.
  7018. * @param x Number to start search from.
  7019. * @return Next highest power of two.
  7020. */
  7021. Tools.CeilingPOT = function (x) {
  7022. x--;
  7023. x |= x >> 1;
  7024. x |= x >> 2;
  7025. x |= x >> 4;
  7026. x |= x >> 8;
  7027. x |= x >> 16;
  7028. x++;
  7029. return x;
  7030. };
  7031. /**
  7032. * Find the next lowest power of two.
  7033. * @param x Number to start search from.
  7034. * @return Next lowest power of two.
  7035. */
  7036. Tools.FloorPOT = function (x) {
  7037. x = x | (x >> 1);
  7038. x = x | (x >> 2);
  7039. x = x | (x >> 4);
  7040. x = x | (x >> 8);
  7041. x = x | (x >> 16);
  7042. return x - (x >> 1);
  7043. };
  7044. /**
  7045. * Find the nearest power of two.
  7046. * @param x Number to start search from.
  7047. * @return Next nearest power of two.
  7048. */
  7049. Tools.NearestPOT = function (x) {
  7050. var c = Tools.CeilingPOT(x);
  7051. var f = Tools.FloorPOT(x);
  7052. return (c - x) > (x - f) ? f : c;
  7053. };
  7054. Tools.GetExponentOfTwo = function (value, max, mode) {
  7055. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  7056. var pot;
  7057. switch (mode) {
  7058. case BABYLON.Engine.SCALEMODE_FLOOR:
  7059. pot = Tools.FloorPOT(value);
  7060. break;
  7061. case BABYLON.Engine.SCALEMODE_NEAREST:
  7062. pot = Tools.NearestPOT(value);
  7063. break;
  7064. case BABYLON.Engine.SCALEMODE_CEILING:
  7065. default:
  7066. pot = Tools.CeilingPOT(value);
  7067. break;
  7068. }
  7069. return Math.min(pot, max);
  7070. };
  7071. Tools.GetFilename = function (path) {
  7072. var index = path.lastIndexOf("/");
  7073. if (index < 0)
  7074. return path;
  7075. return path.substring(index + 1);
  7076. };
  7077. Tools.GetFolderPath = function (uri) {
  7078. var index = uri.lastIndexOf("/");
  7079. if (index < 0)
  7080. return "";
  7081. return uri.substring(0, index + 1);
  7082. };
  7083. Tools.GetDOMTextContent = function (element) {
  7084. var result = "";
  7085. var child = element.firstChild;
  7086. while (child) {
  7087. if (child.nodeType === 3) {
  7088. result += child.textContent;
  7089. }
  7090. child = child.nextSibling;
  7091. }
  7092. return result;
  7093. };
  7094. Tools.ToDegrees = function (angle) {
  7095. return angle * 180 / Math.PI;
  7096. };
  7097. Tools.ToRadians = function (angle) {
  7098. return angle * Math.PI / 180;
  7099. };
  7100. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  7101. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  7102. var output = "";
  7103. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  7104. var i = 0;
  7105. var bytes = new Uint8Array(buffer);
  7106. while (i < bytes.length) {
  7107. chr1 = bytes[i++];
  7108. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  7109. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  7110. enc1 = chr1 >> 2;
  7111. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  7112. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  7113. enc4 = chr3 & 63;
  7114. if (isNaN(chr2)) {
  7115. enc3 = enc4 = 64;
  7116. }
  7117. else if (isNaN(chr3)) {
  7118. enc4 = 64;
  7119. }
  7120. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  7121. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  7122. }
  7123. return "data:image/png;base64," + output;
  7124. };
  7125. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  7126. if (bias === void 0) { bias = null; }
  7127. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7128. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7129. for (var index = indexStart; index < indexStart + indexCount; index++) {
  7130. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  7131. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7132. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7133. }
  7134. if (bias) {
  7135. minimum.x -= minimum.x * bias.x + bias.y;
  7136. minimum.y -= minimum.y * bias.x + bias.y;
  7137. minimum.z -= minimum.z * bias.x + bias.y;
  7138. maximum.x += maximum.x * bias.x + bias.y;
  7139. maximum.y += maximum.y * bias.x + bias.y;
  7140. maximum.z += maximum.z * bias.x + bias.y;
  7141. }
  7142. return {
  7143. minimum: minimum,
  7144. maximum: maximum
  7145. };
  7146. };
  7147. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  7148. if (bias === void 0) { bias = null; }
  7149. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7150. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7151. if (!stride) {
  7152. stride = 3;
  7153. }
  7154. for (var index = start; index < start + count; index++) {
  7155. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  7156. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7157. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7158. }
  7159. if (bias) {
  7160. minimum.x -= minimum.x * bias.x + bias.y;
  7161. minimum.y -= minimum.y * bias.x + bias.y;
  7162. minimum.z -= minimum.z * bias.x + bias.y;
  7163. maximum.x += maximum.x * bias.x + bias.y;
  7164. maximum.y += maximum.y * bias.x + bias.y;
  7165. maximum.z += maximum.z * bias.x + bias.y;
  7166. }
  7167. return {
  7168. minimum: minimum,
  7169. maximum: maximum
  7170. };
  7171. };
  7172. Tools.Vector2ArrayFeeder = function (array) {
  7173. return function (index) {
  7174. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  7175. var length = isFloatArray ? array.length / 2 : array.length;
  7176. if (index >= length) {
  7177. return null;
  7178. }
  7179. if (isFloatArray) {
  7180. var fa = array;
  7181. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  7182. }
  7183. var a = array;
  7184. return a[index];
  7185. };
  7186. };
  7187. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  7188. if (bias === void 0) { bias = null; }
  7189. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  7190. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  7191. var i = 0;
  7192. var cur = feeder(i++);
  7193. while (cur) {
  7194. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  7195. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  7196. cur = feeder(i++);
  7197. }
  7198. if (bias) {
  7199. minimum.x -= minimum.x * bias.x + bias.y;
  7200. minimum.y -= minimum.y * bias.x + bias.y;
  7201. maximum.x += maximum.x * bias.x + bias.y;
  7202. maximum.y += maximum.y * bias.x + bias.y;
  7203. }
  7204. return {
  7205. minimum: minimum,
  7206. maximum: maximum
  7207. };
  7208. };
  7209. Tools.MakeArray = function (obj, allowsNullUndefined) {
  7210. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  7211. return null;
  7212. return Array.isArray(obj) ? obj : [obj];
  7213. };
  7214. // Misc.
  7215. Tools.GetPointerPrefix = function () {
  7216. var eventPrefix = "pointer";
  7217. // Check if pointer events are supported
  7218. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  7219. eventPrefix = "mouse";
  7220. }
  7221. return eventPrefix;
  7222. };
  7223. /**
  7224. * @param func - the function to be called
  7225. * @param requester - the object that will request the next frame. Falls back to window.
  7226. */
  7227. Tools.QueueNewFrame = function (func, requester) {
  7228. if (!Tools.IsWindowObjectExist()) {
  7229. return setTimeout(func, 16);
  7230. }
  7231. if (!requester) {
  7232. requester = window;
  7233. }
  7234. if (requester.requestAnimationFrame) {
  7235. return requester.requestAnimationFrame(func);
  7236. }
  7237. else if (requester.msRequestAnimationFrame) {
  7238. return requester.msRequestAnimationFrame(func);
  7239. }
  7240. else if (requester.webkitRequestAnimationFrame) {
  7241. return requester.webkitRequestAnimationFrame(func);
  7242. }
  7243. else if (requester.mozRequestAnimationFrame) {
  7244. return requester.mozRequestAnimationFrame(func);
  7245. }
  7246. else if (requester.oRequestAnimationFrame) {
  7247. return requester.oRequestAnimationFrame(func);
  7248. }
  7249. else {
  7250. return window.setTimeout(func, 16);
  7251. }
  7252. };
  7253. Tools.RequestFullscreen = function (element) {
  7254. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  7255. if (!requestFunction)
  7256. return;
  7257. requestFunction.call(element);
  7258. };
  7259. Tools.ExitFullscreen = function () {
  7260. if (document.exitFullscreen) {
  7261. document.exitFullscreen();
  7262. }
  7263. else if (document.mozCancelFullScreen) {
  7264. document.mozCancelFullScreen();
  7265. }
  7266. else if (document.webkitCancelFullScreen) {
  7267. document.webkitCancelFullScreen();
  7268. }
  7269. else if (document.msCancelFullScreen) {
  7270. document.msCancelFullScreen();
  7271. }
  7272. };
  7273. Tools.SetCorsBehavior = function (url, element) {
  7274. if (url && url.indexOf("data:") === 0) {
  7275. return;
  7276. }
  7277. if (Tools.CorsBehavior) {
  7278. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  7279. element.crossOrigin = Tools.CorsBehavior;
  7280. }
  7281. else {
  7282. var result = Tools.CorsBehavior(url);
  7283. if (result) {
  7284. element.crossOrigin = result;
  7285. }
  7286. }
  7287. }
  7288. };
  7289. // External files
  7290. Tools.CleanUrl = function (url) {
  7291. url = url.replace(/#/mg, "%23");
  7292. return url;
  7293. };
  7294. Tools.LoadImage = function (url, onLoad, onError, database) {
  7295. if (url instanceof ArrayBuffer) {
  7296. url = Tools.EncodeArrayBufferTobase64(url);
  7297. }
  7298. url = Tools.CleanUrl(url);
  7299. url = Tools.PreprocessUrl(url);
  7300. var img = new Image();
  7301. Tools.SetCorsBehavior(url, img);
  7302. img.onload = function () {
  7303. onLoad(img);
  7304. };
  7305. img.onerror = function (err) {
  7306. Tools.Error("Error while trying to load image: " + url);
  7307. if (onError) {
  7308. onError("Error while trying to load image: " + url, err);
  7309. }
  7310. };
  7311. var noIndexedDB = function () {
  7312. img.src = url;
  7313. };
  7314. var loadFromIndexedDB = function () {
  7315. if (database) {
  7316. database.loadImageFromDB(url, img);
  7317. }
  7318. };
  7319. //ANY database to do!
  7320. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  7321. database.openAsync(loadFromIndexedDB, noIndexedDB);
  7322. }
  7323. else {
  7324. if (url.indexOf("file:") !== -1) {
  7325. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  7326. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  7327. try {
  7328. var blobURL;
  7329. try {
  7330. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  7331. }
  7332. catch (ex) {
  7333. // Chrome doesn't support oneTimeOnly parameter
  7334. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  7335. }
  7336. img.src = blobURL;
  7337. }
  7338. catch (e) {
  7339. img.src = "";
  7340. }
  7341. return img;
  7342. }
  7343. }
  7344. noIndexedDB();
  7345. }
  7346. return img;
  7347. };
  7348. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  7349. url = Tools.CleanUrl(url);
  7350. url = Tools.PreprocessUrl(url);
  7351. // If file and file input are set
  7352. if (url.indexOf("file:") !== -1) {
  7353. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  7354. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  7355. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  7356. }
  7357. }
  7358. var loadUrl = Tools.BaseUrl + url;
  7359. var aborted = false;
  7360. var fileRequest = {
  7361. onCompleteObservable: new BABYLON.Observable(),
  7362. abort: function () { return aborted = true; },
  7363. };
  7364. var requestFile = function () {
  7365. var request = new XMLHttpRequest();
  7366. var retryHandle = null;
  7367. fileRequest.abort = function () {
  7368. aborted = true;
  7369. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  7370. request.abort();
  7371. }
  7372. if (retryHandle !== null) {
  7373. clearTimeout(retryHandle);
  7374. retryHandle = null;
  7375. }
  7376. };
  7377. var retryLoop = function (retryIndex) {
  7378. request.open('GET', loadUrl, true);
  7379. if (useArrayBuffer) {
  7380. request.responseType = "arraybuffer";
  7381. }
  7382. if (onProgress) {
  7383. request.addEventListener("progress", onProgress);
  7384. }
  7385. var onLoadEnd = function () {
  7386. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  7387. };
  7388. request.addEventListener("loadend", onLoadEnd);
  7389. var onReadyStateChange = function () {
  7390. if (aborted) {
  7391. return;
  7392. }
  7393. // In case of undefined state in some browsers.
  7394. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  7395. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  7396. request.removeEventListener("readystatechange", onReadyStateChange);
  7397. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  7398. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  7399. return;
  7400. }
  7401. var retryStrategy = Tools.DefaultRetryStrategy;
  7402. if (retryStrategy) {
  7403. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  7404. if (waitTime !== -1) {
  7405. // Prevent the request from completing for retry.
  7406. request.removeEventListener("loadend", onLoadEnd);
  7407. request = new XMLHttpRequest();
  7408. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  7409. return;
  7410. }
  7411. }
  7412. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  7413. if (onError) {
  7414. onError(request, e);
  7415. }
  7416. else {
  7417. throw e;
  7418. }
  7419. }
  7420. };
  7421. request.addEventListener("readystatechange", onReadyStateChange);
  7422. request.send();
  7423. };
  7424. retryLoop(0);
  7425. };
  7426. // Caching all files
  7427. if (database && database.enableSceneOffline) {
  7428. var noIndexedDB_1 = function () {
  7429. if (!aborted) {
  7430. requestFile();
  7431. }
  7432. };
  7433. var loadFromIndexedDB = function () {
  7434. // TODO: database needs to support aborting and should return a IFileRequest
  7435. if (aborted) {
  7436. return;
  7437. }
  7438. if (database) {
  7439. database.loadFileFromDB(url, function (data) {
  7440. if (!aborted) {
  7441. onSuccess(data);
  7442. }
  7443. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  7444. }, onProgress ? function (event) {
  7445. if (!aborted) {
  7446. onProgress(event);
  7447. }
  7448. } : undefined, noIndexedDB_1, useArrayBuffer);
  7449. }
  7450. };
  7451. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  7452. }
  7453. else {
  7454. requestFile();
  7455. }
  7456. return fileRequest;
  7457. };
  7458. /**
  7459. * Load a script (identified by an url). When the url returns, the
  7460. * content of this file is added into a new script element, attached to the DOM (body element)
  7461. */
  7462. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  7463. var head = document.getElementsByTagName('head')[0];
  7464. var script = document.createElement('script');
  7465. script.type = 'text/javascript';
  7466. script.src = scriptUrl;
  7467. script.onload = function () {
  7468. if (onSuccess) {
  7469. onSuccess();
  7470. }
  7471. };
  7472. script.onerror = function (e) {
  7473. if (onError) {
  7474. onError("Unable to load script", e);
  7475. }
  7476. };
  7477. head.appendChild(script);
  7478. };
  7479. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  7480. var reader = new FileReader();
  7481. var request = {
  7482. onCompleteObservable: new BABYLON.Observable(),
  7483. abort: function () { return reader.abort(); },
  7484. };
  7485. reader.onloadend = function (e) {
  7486. request.onCompleteObservable.notifyObservers(request);
  7487. };
  7488. reader.onload = function (e) {
  7489. //target doesn't have result from ts 1.3
  7490. callback(e.target['result']);
  7491. };
  7492. reader.onprogress = progressCallback;
  7493. reader.readAsDataURL(fileToLoad);
  7494. return request;
  7495. };
  7496. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  7497. var reader = new FileReader();
  7498. var request = {
  7499. onCompleteObservable: new BABYLON.Observable(),
  7500. abort: function () { return reader.abort(); },
  7501. };
  7502. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  7503. reader.onerror = function (e) {
  7504. Tools.Log("Error while reading file: " + fileToLoad.name);
  7505. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  7506. };
  7507. reader.onload = function (e) {
  7508. //target doesn't have result from ts 1.3
  7509. callback(e.target['result']);
  7510. };
  7511. if (progressCallBack) {
  7512. reader.onprogress = progressCallBack;
  7513. }
  7514. if (!useArrayBuffer) {
  7515. // Asynchronous read
  7516. reader.readAsText(fileToLoad);
  7517. }
  7518. else {
  7519. reader.readAsArrayBuffer(fileToLoad);
  7520. }
  7521. return request;
  7522. };
  7523. //returns a downloadable url to a file content.
  7524. Tools.FileAsURL = function (content) {
  7525. var fileBlob = new Blob([content]);
  7526. var url = window.URL || window.webkitURL;
  7527. var link = url.createObjectURL(fileBlob);
  7528. return link;
  7529. };
  7530. // Misc.
  7531. Tools.Format = function (value, decimals) {
  7532. if (decimals === void 0) { decimals = 2; }
  7533. return value.toFixed(decimals);
  7534. };
  7535. Tools.CheckExtends = function (v, min, max) {
  7536. if (v.x < min.x)
  7537. min.x = v.x;
  7538. if (v.y < min.y)
  7539. min.y = v.y;
  7540. if (v.z < min.z)
  7541. min.z = v.z;
  7542. if (v.x > max.x)
  7543. max.x = v.x;
  7544. if (v.y > max.y)
  7545. max.y = v.y;
  7546. if (v.z > max.z)
  7547. max.z = v.z;
  7548. };
  7549. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  7550. for (var prop in source) {
  7551. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  7552. continue;
  7553. }
  7554. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  7555. continue;
  7556. }
  7557. var sourceValue = source[prop];
  7558. var typeOfSourceValue = typeof sourceValue;
  7559. if (typeOfSourceValue === "function") {
  7560. continue;
  7561. }
  7562. if (typeOfSourceValue === "object") {
  7563. if (sourceValue instanceof Array) {
  7564. destination[prop] = [];
  7565. if (sourceValue.length > 0) {
  7566. if (typeof sourceValue[0] == "object") {
  7567. for (var index = 0; index < sourceValue.length; index++) {
  7568. var clonedValue = cloneValue(sourceValue[index], destination);
  7569. if (destination[prop].indexOf(clonedValue) === -1) {
  7570. destination[prop].push(clonedValue);
  7571. }
  7572. }
  7573. }
  7574. else {
  7575. destination[prop] = sourceValue.slice(0);
  7576. }
  7577. }
  7578. }
  7579. else {
  7580. destination[prop] = cloneValue(sourceValue, destination);
  7581. }
  7582. }
  7583. else {
  7584. destination[prop] = sourceValue;
  7585. }
  7586. }
  7587. };
  7588. Tools.IsEmpty = function (obj) {
  7589. for (var i in obj) {
  7590. if (obj.hasOwnProperty(i)) {
  7591. return false;
  7592. }
  7593. }
  7594. return true;
  7595. };
  7596. Tools.RegisterTopRootEvents = function (events) {
  7597. for (var index = 0; index < events.length; index++) {
  7598. var event = events[index];
  7599. window.addEventListener(event.name, event.handler, false);
  7600. try {
  7601. if (window.parent) {
  7602. window.parent.addEventListener(event.name, event.handler, false);
  7603. }
  7604. }
  7605. catch (e) {
  7606. // Silently fails...
  7607. }
  7608. }
  7609. };
  7610. Tools.UnregisterTopRootEvents = function (events) {
  7611. for (var index = 0; index < events.length; index++) {
  7612. var event = events[index];
  7613. window.removeEventListener(event.name, event.handler);
  7614. try {
  7615. if (window.parent) {
  7616. window.parent.removeEventListener(event.name, event.handler);
  7617. }
  7618. }
  7619. catch (e) {
  7620. // Silently fails...
  7621. }
  7622. }
  7623. };
  7624. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  7625. if (mimeType === void 0) { mimeType = "image/png"; }
  7626. // Read the contents of the framebuffer
  7627. var numberOfChannelsByLine = width * 4;
  7628. var halfHeight = height / 2;
  7629. //Reading datas from WebGL
  7630. var data = engine.readPixels(0, 0, width, height);
  7631. //To flip image on Y axis.
  7632. for (var i = 0; i < halfHeight; i++) {
  7633. for (var j = 0; j < numberOfChannelsByLine; j++) {
  7634. var currentCell = j + i * numberOfChannelsByLine;
  7635. var targetLine = height - i - 1;
  7636. var targetCell = j + targetLine * numberOfChannelsByLine;
  7637. var temp = data[currentCell];
  7638. data[currentCell] = data[targetCell];
  7639. data[targetCell] = temp;
  7640. }
  7641. }
  7642. // Create a 2D canvas to store the result
  7643. if (!screenshotCanvas) {
  7644. screenshotCanvas = document.createElement('canvas');
  7645. }
  7646. screenshotCanvas.width = width;
  7647. screenshotCanvas.height = height;
  7648. var context = screenshotCanvas.getContext('2d');
  7649. if (context) {
  7650. // Copy the pixels to a 2D canvas
  7651. var imageData = context.createImageData(width, height);
  7652. var castData = (imageData.data);
  7653. castData.set(data);
  7654. context.putImageData(imageData, 0, 0);
  7655. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  7656. }
  7657. };
  7658. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  7659. if (mimeType === void 0) { mimeType = "image/png"; }
  7660. var base64Image = screenshotCanvas.toDataURL(mimeType);
  7661. if (successCallback) {
  7662. successCallback(base64Image);
  7663. }
  7664. else {
  7665. // We need HTMLCanvasElement.toBlob for HD screenshots
  7666. if (!screenshotCanvas.toBlob) {
  7667. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  7668. screenshotCanvas.toBlob = function (callback, type, quality) {
  7669. var _this = this;
  7670. setTimeout(function () {
  7671. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  7672. for (var i = 0; i < len; i++) {
  7673. arr[i] = binStr.charCodeAt(i);
  7674. }
  7675. callback(new Blob([arr], { type: type || 'image/png' }));
  7676. });
  7677. };
  7678. }
  7679. screenshotCanvas.toBlob(function (blob) {
  7680. var url = URL.createObjectURL(blob);
  7681. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  7682. if (("download" in document.createElement("a"))) {
  7683. var a = window.document.createElement("a");
  7684. a.href = url;
  7685. if (fileName) {
  7686. a.setAttribute("download", fileName);
  7687. }
  7688. else {
  7689. var date = new Date();
  7690. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  7691. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  7692. }
  7693. window.document.body.appendChild(a);
  7694. a.addEventListener("click", function () {
  7695. if (a.parentElement) {
  7696. a.parentElement.removeChild(a);
  7697. }
  7698. });
  7699. a.click();
  7700. }
  7701. else {
  7702. var newWindow = window.open("");
  7703. if (!newWindow)
  7704. return;
  7705. var img = newWindow.document.createElement("img");
  7706. img.onload = function () {
  7707. // no longer need to read the blob so it's revoked
  7708. URL.revokeObjectURL(url);
  7709. };
  7710. img.src = url;
  7711. newWindow.document.body.appendChild(img);
  7712. }
  7713. });
  7714. }
  7715. };
  7716. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  7717. if (mimeType === void 0) { mimeType = "image/png"; }
  7718. var width;
  7719. var height;
  7720. // If a precision value is specified
  7721. if (size.precision) {
  7722. width = Math.round(engine.getRenderWidth() * size.precision);
  7723. height = Math.round(width / engine.getAspectRatio(camera));
  7724. }
  7725. else if (size.width && size.height) {
  7726. width = size.width;
  7727. height = size.height;
  7728. }
  7729. else if (size.width && !size.height) {
  7730. width = size.width;
  7731. height = Math.round(width / engine.getAspectRatio(camera));
  7732. }
  7733. else if (size.height && !size.width) {
  7734. height = size.height;
  7735. width = Math.round(height * engine.getAspectRatio(camera));
  7736. }
  7737. else if (!isNaN(size)) {
  7738. height = size;
  7739. width = size;
  7740. }
  7741. else {
  7742. Tools.Error("Invalid 'size' parameter !");
  7743. return;
  7744. }
  7745. if (!screenshotCanvas) {
  7746. screenshotCanvas = document.createElement('canvas');
  7747. }
  7748. screenshotCanvas.width = width;
  7749. screenshotCanvas.height = height;
  7750. var renderContext = screenshotCanvas.getContext("2d");
  7751. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  7752. var newWidth = width;
  7753. var newHeight = newWidth / ratio;
  7754. if (newHeight > height) {
  7755. newHeight = height;
  7756. newWidth = newHeight * ratio;
  7757. }
  7758. var offsetX = Math.max(0, width - newWidth) / 2;
  7759. var offsetY = Math.max(0, height - newHeight) / 2;
  7760. var renderingCanvas = engine.getRenderingCanvas();
  7761. if (renderContext && renderingCanvas) {
  7762. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  7763. }
  7764. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  7765. };
  7766. /**
  7767. * Generates an image screenshot from the specified camera.
  7768. *
  7769. * @param engine The engine to use for rendering
  7770. * @param camera The camera to use for rendering
  7771. * @param size This parameter can be set to a single number or to an object with the
  7772. * following (optional) properties: precision, width, height. If a single number is passed,
  7773. * it will be used for both width and height. If an object is passed, the screenshot size
  7774. * will be derived from the parameters. The precision property is a multiplier allowing
  7775. * rendering at a higher or lower resolution.
  7776. * @param successCallback The callback receives a single parameter which contains the
  7777. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  7778. * src parameter of an <img> to display it.
  7779. * @param mimeType The MIME type of the screenshot image (default: image/png).
  7780. * Check your browser for supported MIME types.
  7781. * @param samples Texture samples (default: 1)
  7782. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  7783. * @param fileName A name for for the downloaded file.
  7784. * @constructor
  7785. */
  7786. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  7787. if (mimeType === void 0) { mimeType = "image/png"; }
  7788. if (samples === void 0) { samples = 1; }
  7789. if (antialiasing === void 0) { antialiasing = false; }
  7790. var width;
  7791. var height;
  7792. //If a precision value is specified
  7793. if (size.precision) {
  7794. width = Math.round(engine.getRenderWidth() * size.precision);
  7795. height = Math.round(width / engine.getAspectRatio(camera));
  7796. size = { width: width, height: height };
  7797. }
  7798. else if (size.width && size.height) {
  7799. width = size.width;
  7800. height = size.height;
  7801. }
  7802. else if (size.width && !size.height) {
  7803. width = size.width;
  7804. height = Math.round(width / engine.getAspectRatio(camera));
  7805. size = { width: width, height: height };
  7806. }
  7807. else if (size.height && !size.width) {
  7808. height = size.height;
  7809. width = Math.round(height * engine.getAspectRatio(camera));
  7810. size = { width: width, height: height };
  7811. }
  7812. else if (!isNaN(size)) {
  7813. height = size;
  7814. width = size;
  7815. }
  7816. else {
  7817. Tools.Error("Invalid 'size' parameter !");
  7818. return;
  7819. }
  7820. var scene = camera.getScene();
  7821. var previousCamera = null;
  7822. if (scene.activeCamera !== camera) {
  7823. previousCamera = scene.activeCamera;
  7824. scene.activeCamera = camera;
  7825. }
  7826. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  7827. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  7828. texture.renderList = null;
  7829. texture.samples = samples;
  7830. if (antialiasing) {
  7831. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  7832. }
  7833. texture.onAfterRenderObservable.add(function () {
  7834. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  7835. });
  7836. scene.incrementRenderId();
  7837. scene.resetCachedMaterial();
  7838. texture.render(true);
  7839. texture.dispose();
  7840. if (previousCamera) {
  7841. scene.activeCamera = previousCamera;
  7842. }
  7843. camera.getProjectionMatrix(true); // Force cache refresh;
  7844. };
  7845. // XHR response validator for local file scenario
  7846. Tools.ValidateXHRData = function (xhr, dataType) {
  7847. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  7848. if (dataType === void 0) { dataType = 7; }
  7849. try {
  7850. if (dataType & 1) {
  7851. if (xhr.responseText && xhr.responseText.length > 0) {
  7852. return true;
  7853. }
  7854. else if (dataType === 1) {
  7855. return false;
  7856. }
  7857. }
  7858. if (dataType & 2) {
  7859. // Check header width and height since there is no "TGA" magic number
  7860. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  7861. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  7862. return true;
  7863. }
  7864. else if (dataType === 2) {
  7865. return false;
  7866. }
  7867. }
  7868. if (dataType & 4) {
  7869. // Check for the "DDS" magic number
  7870. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  7871. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  7872. return true;
  7873. }
  7874. else {
  7875. return false;
  7876. }
  7877. }
  7878. }
  7879. catch (e) {
  7880. // Global protection
  7881. }
  7882. return false;
  7883. };
  7884. /**
  7885. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  7886. * Be aware Math.random() could cause collisions, but:
  7887. * "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"
  7888. */
  7889. Tools.RandomId = function () {
  7890. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  7891. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  7892. return v.toString(16);
  7893. });
  7894. };
  7895. Object.defineProperty(Tools, "NoneLogLevel", {
  7896. get: function () {
  7897. return Tools._NoneLogLevel;
  7898. },
  7899. enumerable: true,
  7900. configurable: true
  7901. });
  7902. Object.defineProperty(Tools, "MessageLogLevel", {
  7903. get: function () {
  7904. return Tools._MessageLogLevel;
  7905. },
  7906. enumerable: true,
  7907. configurable: true
  7908. });
  7909. Object.defineProperty(Tools, "WarningLogLevel", {
  7910. get: function () {
  7911. return Tools._WarningLogLevel;
  7912. },
  7913. enumerable: true,
  7914. configurable: true
  7915. });
  7916. Object.defineProperty(Tools, "ErrorLogLevel", {
  7917. get: function () {
  7918. return Tools._ErrorLogLevel;
  7919. },
  7920. enumerable: true,
  7921. configurable: true
  7922. });
  7923. Object.defineProperty(Tools, "AllLogLevel", {
  7924. get: function () {
  7925. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  7926. },
  7927. enumerable: true,
  7928. configurable: true
  7929. });
  7930. Tools._AddLogEntry = function (entry) {
  7931. Tools._LogCache = entry + Tools._LogCache;
  7932. if (Tools.OnNewCacheEntry) {
  7933. Tools.OnNewCacheEntry(entry);
  7934. }
  7935. };
  7936. Tools._FormatMessage = function (message) {
  7937. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  7938. var date = new Date();
  7939. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  7940. };
  7941. Tools._LogDisabled = function (message) {
  7942. // nothing to do
  7943. };
  7944. Tools._LogEnabled = function (message) {
  7945. var formattedMessage = Tools._FormatMessage(message);
  7946. console.log("BJS - " + formattedMessage);
  7947. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  7948. Tools._AddLogEntry(entry);
  7949. };
  7950. Tools._WarnDisabled = function (message) {
  7951. // nothing to do
  7952. };
  7953. Tools._WarnEnabled = function (message) {
  7954. var formattedMessage = Tools._FormatMessage(message);
  7955. console.warn("BJS - " + formattedMessage);
  7956. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  7957. Tools._AddLogEntry(entry);
  7958. };
  7959. Tools._ErrorDisabled = function (message) {
  7960. // nothing to do
  7961. };
  7962. Tools._ErrorEnabled = function (message) {
  7963. Tools.errorsCount++;
  7964. var formattedMessage = Tools._FormatMessage(message);
  7965. console.error("BJS - " + formattedMessage);
  7966. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  7967. Tools._AddLogEntry(entry);
  7968. };
  7969. Object.defineProperty(Tools, "LogCache", {
  7970. get: function () {
  7971. return Tools._LogCache;
  7972. },
  7973. enumerable: true,
  7974. configurable: true
  7975. });
  7976. Tools.ClearLogCache = function () {
  7977. Tools._LogCache = "";
  7978. Tools.errorsCount = 0;
  7979. };
  7980. Object.defineProperty(Tools, "LogLevels", {
  7981. set: function (level) {
  7982. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  7983. Tools.Log = Tools._LogEnabled;
  7984. }
  7985. else {
  7986. Tools.Log = Tools._LogDisabled;
  7987. }
  7988. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  7989. Tools.Warn = Tools._WarnEnabled;
  7990. }
  7991. else {
  7992. Tools.Warn = Tools._WarnDisabled;
  7993. }
  7994. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  7995. Tools.Error = Tools._ErrorEnabled;
  7996. }
  7997. else {
  7998. Tools.Error = Tools._ErrorDisabled;
  7999. }
  8000. },
  8001. enumerable: true,
  8002. configurable: true
  8003. });
  8004. Tools.IsWindowObjectExist = function () {
  8005. return (typeof window) !== "undefined";
  8006. };
  8007. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  8008. get: function () {
  8009. return Tools._PerformanceNoneLogLevel;
  8010. },
  8011. enumerable: true,
  8012. configurable: true
  8013. });
  8014. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  8015. get: function () {
  8016. return Tools._PerformanceUserMarkLogLevel;
  8017. },
  8018. enumerable: true,
  8019. configurable: true
  8020. });
  8021. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  8022. get: function () {
  8023. return Tools._PerformanceConsoleLogLevel;
  8024. },
  8025. enumerable: true,
  8026. configurable: true
  8027. });
  8028. Object.defineProperty(Tools, "PerformanceLogLevel", {
  8029. set: function (level) {
  8030. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  8031. Tools.StartPerformanceCounter = Tools._StartUserMark;
  8032. Tools.EndPerformanceCounter = Tools._EndUserMark;
  8033. return;
  8034. }
  8035. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  8036. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  8037. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  8038. return;
  8039. }
  8040. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  8041. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  8042. },
  8043. enumerable: true,
  8044. configurable: true
  8045. });
  8046. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  8047. };
  8048. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  8049. };
  8050. Tools._StartUserMark = function (counterName, condition) {
  8051. if (condition === void 0) { condition = true; }
  8052. if (!Tools._performance) {
  8053. if (!Tools.IsWindowObjectExist()) {
  8054. return;
  8055. }
  8056. Tools._performance = window.performance;
  8057. }
  8058. if (!condition || !Tools._performance.mark) {
  8059. return;
  8060. }
  8061. Tools._performance.mark(counterName + "-Begin");
  8062. };
  8063. Tools._EndUserMark = function (counterName, condition) {
  8064. if (condition === void 0) { condition = true; }
  8065. if (!condition || !Tools._performance.mark) {
  8066. return;
  8067. }
  8068. Tools._performance.mark(counterName + "-End");
  8069. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  8070. };
  8071. Tools._StartPerformanceConsole = function (counterName, condition) {
  8072. if (condition === void 0) { condition = true; }
  8073. if (!condition) {
  8074. return;
  8075. }
  8076. Tools._StartUserMark(counterName, condition);
  8077. if (console.time) {
  8078. console.time(counterName);
  8079. }
  8080. };
  8081. Tools._EndPerformanceConsole = function (counterName, condition) {
  8082. if (condition === void 0) { condition = true; }
  8083. if (!condition) {
  8084. return;
  8085. }
  8086. Tools._EndUserMark(counterName, condition);
  8087. if (console.time) {
  8088. console.timeEnd(counterName);
  8089. }
  8090. };
  8091. Object.defineProperty(Tools, "Now", {
  8092. get: function () {
  8093. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  8094. return window.performance.now();
  8095. }
  8096. return new Date().getTime();
  8097. },
  8098. enumerable: true,
  8099. configurable: true
  8100. });
  8101. /**
  8102. * This method will return the name of the class used to create the instance of the given object.
  8103. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  8104. * @param object the object to get the class name from
  8105. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  8106. */
  8107. Tools.GetClassName = function (object, isType) {
  8108. if (isType === void 0) { isType = false; }
  8109. var name = null;
  8110. if (!isType && object.getClassName) {
  8111. name = object.getClassName();
  8112. }
  8113. else {
  8114. if (object instanceof Object) {
  8115. var classObj = isType ? object : Object.getPrototypeOf(object);
  8116. name = classObj.constructor["__bjsclassName__"];
  8117. }
  8118. if (!name) {
  8119. name = typeof object;
  8120. }
  8121. }
  8122. return name;
  8123. };
  8124. Tools.First = function (array, predicate) {
  8125. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  8126. var el = array_1[_i];
  8127. if (predicate(el)) {
  8128. return el;
  8129. }
  8130. }
  8131. return null;
  8132. };
  8133. /**
  8134. * This method will return the name of the full name of the class, including its owning module (if any).
  8135. * 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).
  8136. * @param object the object to get the class name from
  8137. * @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.
  8138. */
  8139. Tools.getFullClassName = function (object, isType) {
  8140. if (isType === void 0) { isType = false; }
  8141. var className = null;
  8142. var moduleName = null;
  8143. if (!isType && object.getClassName) {
  8144. className = object.getClassName();
  8145. }
  8146. else {
  8147. if (object instanceof Object) {
  8148. var classObj = isType ? object : Object.getPrototypeOf(object);
  8149. className = classObj.constructor["__bjsclassName__"];
  8150. moduleName = classObj.constructor["__bjsmoduleName__"];
  8151. }
  8152. if (!className) {
  8153. className = typeof object;
  8154. }
  8155. }
  8156. if (!className) {
  8157. return null;
  8158. }
  8159. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  8160. };
  8161. /**
  8162. * 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.
  8163. * @param array
  8164. */
  8165. Tools.arrayOrStringFeeder = function (array) {
  8166. return function (index) {
  8167. if (index >= array.length) {
  8168. return null;
  8169. }
  8170. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  8171. if (val && val.getHashCode) {
  8172. val = val.getHashCode();
  8173. }
  8174. if (typeof val === "string") {
  8175. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  8176. }
  8177. return val;
  8178. };
  8179. };
  8180. /**
  8181. * Compute the hashCode of a stream of number
  8182. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  8183. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  8184. * @return the hash code computed
  8185. */
  8186. Tools.hashCodeFromStream = function (feeder) {
  8187. // Based from here: http://stackoverflow.com/a/7616484/802124
  8188. var hash = 0;
  8189. var index = 0;
  8190. var chr = feeder(index++);
  8191. while (chr != null) {
  8192. hash = ((hash << 5) - hash) + chr;
  8193. hash |= 0; // Convert to 32bit integer
  8194. chr = feeder(index++);
  8195. }
  8196. return hash;
  8197. };
  8198. Tools.BaseUrl = "";
  8199. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  8200. /**
  8201. * Default behaviour for cors in the application.
  8202. * It can be a string if the expected behavior is identical in the entire app.
  8203. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  8204. */
  8205. Tools.CorsBehavior = "anonymous";
  8206. Tools.UseFallbackTexture = true;
  8207. /**
  8208. * Use this object to register external classes like custom textures or material
  8209. * to allow the laoders to instantiate them
  8210. */
  8211. Tools.RegisteredExternalClasses = {};
  8212. // Used in case of a texture loading problem
  8213. 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";
  8214. Tools.PreprocessUrl = function (url) {
  8215. return url;
  8216. };
  8217. // Logs
  8218. Tools._NoneLogLevel = 0;
  8219. Tools._MessageLogLevel = 1;
  8220. Tools._WarningLogLevel = 2;
  8221. Tools._ErrorLogLevel = 4;
  8222. Tools._LogCache = "";
  8223. Tools.errorsCount = 0;
  8224. Tools.Log = Tools._LogEnabled;
  8225. Tools.Warn = Tools._WarnEnabled;
  8226. Tools.Error = Tools._ErrorEnabled;
  8227. // Performances
  8228. Tools._PerformanceNoneLogLevel = 0;
  8229. Tools._PerformanceUserMarkLogLevel = 1;
  8230. Tools._PerformanceConsoleLogLevel = 2;
  8231. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  8232. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  8233. return Tools;
  8234. }());
  8235. BABYLON.Tools = Tools;
  8236. /**
  8237. * This class is used to track a performance counter which is number based.
  8238. * The user has access to many properties which give statistics of different nature
  8239. *
  8240. * The implementer can track two kinds of Performance Counter: time and count
  8241. * 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.
  8242. * 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.
  8243. */
  8244. var PerfCounter = /** @class */ (function () {
  8245. function PerfCounter() {
  8246. this._startMonitoringTime = 0;
  8247. this._min = 0;
  8248. this._max = 0;
  8249. this._average = 0;
  8250. this._lastSecAverage = 0;
  8251. this._current = 0;
  8252. this._totalValueCount = 0;
  8253. this._totalAccumulated = 0;
  8254. this._lastSecAccumulated = 0;
  8255. this._lastSecTime = 0;
  8256. this._lastSecValueCount = 0;
  8257. }
  8258. Object.defineProperty(PerfCounter.prototype, "min", {
  8259. /**
  8260. * Returns the smallest value ever
  8261. */
  8262. get: function () {
  8263. return this._min;
  8264. },
  8265. enumerable: true,
  8266. configurable: true
  8267. });
  8268. Object.defineProperty(PerfCounter.prototype, "max", {
  8269. /**
  8270. * Returns the biggest value ever
  8271. */
  8272. get: function () {
  8273. return this._max;
  8274. },
  8275. enumerable: true,
  8276. configurable: true
  8277. });
  8278. Object.defineProperty(PerfCounter.prototype, "average", {
  8279. /**
  8280. * Returns the average value since the performance counter is running
  8281. */
  8282. get: function () {
  8283. return this._average;
  8284. },
  8285. enumerable: true,
  8286. configurable: true
  8287. });
  8288. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  8289. /**
  8290. * Returns the average value of the last second the counter was monitored
  8291. */
  8292. get: function () {
  8293. return this._lastSecAverage;
  8294. },
  8295. enumerable: true,
  8296. configurable: true
  8297. });
  8298. Object.defineProperty(PerfCounter.prototype, "current", {
  8299. /**
  8300. * Returns the current value
  8301. */
  8302. get: function () {
  8303. return this._current;
  8304. },
  8305. enumerable: true,
  8306. configurable: true
  8307. });
  8308. Object.defineProperty(PerfCounter.prototype, "total", {
  8309. get: function () {
  8310. return this._totalAccumulated;
  8311. },
  8312. enumerable: true,
  8313. configurable: true
  8314. });
  8315. Object.defineProperty(PerfCounter.prototype, "count", {
  8316. get: function () {
  8317. return this._totalValueCount;
  8318. },
  8319. enumerable: true,
  8320. configurable: true
  8321. });
  8322. /**
  8323. * Call this method to start monitoring a new frame.
  8324. * 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.
  8325. */
  8326. PerfCounter.prototype.fetchNewFrame = function () {
  8327. this._totalValueCount++;
  8328. this._current = 0;
  8329. this._lastSecValueCount++;
  8330. };
  8331. /**
  8332. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  8333. * @param newCount the count value to add to the monitored count
  8334. * @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.
  8335. */
  8336. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  8337. if (!PerfCounter.Enabled) {
  8338. return;
  8339. }
  8340. this._current += newCount;
  8341. if (fetchResult) {
  8342. this._fetchResult();
  8343. }
  8344. };
  8345. /**
  8346. * Start monitoring this performance counter
  8347. */
  8348. PerfCounter.prototype.beginMonitoring = function () {
  8349. if (!PerfCounter.Enabled) {
  8350. return;
  8351. }
  8352. this._startMonitoringTime = Tools.Now;
  8353. };
  8354. /**
  8355. * Compute the time lapsed since the previous beginMonitoring() call.
  8356. * @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
  8357. */
  8358. PerfCounter.prototype.endMonitoring = function (newFrame) {
  8359. if (newFrame === void 0) { newFrame = true; }
  8360. if (!PerfCounter.Enabled) {
  8361. return;
  8362. }
  8363. if (newFrame) {
  8364. this.fetchNewFrame();
  8365. }
  8366. var currentTime = Tools.Now;
  8367. this._current = currentTime - this._startMonitoringTime;
  8368. if (newFrame) {
  8369. this._fetchResult();
  8370. }
  8371. };
  8372. PerfCounter.prototype._fetchResult = function () {
  8373. this._totalAccumulated += this._current;
  8374. this._lastSecAccumulated += this._current;
  8375. // Min/Max update
  8376. this._min = Math.min(this._min, this._current);
  8377. this._max = Math.max(this._max, this._current);
  8378. this._average = this._totalAccumulated / this._totalValueCount;
  8379. // Reset last sec?
  8380. var now = Tools.Now;
  8381. if ((now - this._lastSecTime) > 1000) {
  8382. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  8383. this._lastSecTime = now;
  8384. this._lastSecAccumulated = 0;
  8385. this._lastSecValueCount = 0;
  8386. }
  8387. };
  8388. PerfCounter.Enabled = true;
  8389. return PerfCounter;
  8390. }());
  8391. BABYLON.PerfCounter = PerfCounter;
  8392. /**
  8393. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  8394. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  8395. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  8396. * @param name The name of the class, case should be preserved
  8397. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  8398. */
  8399. function className(name, module) {
  8400. return function (target) {
  8401. target["__bjsclassName__"] = name;
  8402. target["__bjsmoduleName__"] = (module != null) ? module : null;
  8403. };
  8404. }
  8405. BABYLON.className = className;
  8406. /**
  8407. * An implementation of a loop for asynchronous functions.
  8408. */
  8409. var AsyncLoop = /** @class */ (function () {
  8410. /**
  8411. * Constroctor.
  8412. * @param iterations the number of iterations.
  8413. * @param _fn the function to run each iteration
  8414. * @param _successCallback the callback that will be called upon succesful execution
  8415. * @param offset starting offset.
  8416. */
  8417. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  8418. if (offset === void 0) { offset = 0; }
  8419. this.iterations = iterations;
  8420. this._fn = _fn;
  8421. this._successCallback = _successCallback;
  8422. this.index = offset - 1;
  8423. this._done = false;
  8424. }
  8425. /**
  8426. * Execute the next iteration. Must be called after the last iteration was finished.
  8427. */
  8428. AsyncLoop.prototype.executeNext = function () {
  8429. if (!this._done) {
  8430. if (this.index + 1 < this.iterations) {
  8431. ++this.index;
  8432. this._fn(this);
  8433. }
  8434. else {
  8435. this.breakLoop();
  8436. }
  8437. }
  8438. };
  8439. /**
  8440. * Break the loop and run the success callback.
  8441. */
  8442. AsyncLoop.prototype.breakLoop = function () {
  8443. this._done = true;
  8444. this._successCallback();
  8445. };
  8446. /**
  8447. * Helper function
  8448. */
  8449. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  8450. if (offset === void 0) { offset = 0; }
  8451. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  8452. loop.executeNext();
  8453. return loop;
  8454. };
  8455. /**
  8456. * A for-loop that will run a given number of iterations synchronous and the rest async.
  8457. * @param iterations total number of iterations
  8458. * @param syncedIterations number of synchronous iterations in each async iteration.
  8459. * @param fn the function to call each iteration.
  8460. * @param callback a success call back that will be called when iterating stops.
  8461. * @param breakFunction a break condition (optional)
  8462. * @param timeout timeout settings for the setTimeout function. default - 0.
  8463. * @constructor
  8464. */
  8465. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  8466. if (timeout === void 0) { timeout = 0; }
  8467. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  8468. if (breakFunction && breakFunction())
  8469. loop.breakLoop();
  8470. else {
  8471. setTimeout(function () {
  8472. for (var i = 0; i < syncedIterations; ++i) {
  8473. var iteration = (loop.index * syncedIterations) + i;
  8474. if (iteration >= iterations)
  8475. break;
  8476. fn(iteration);
  8477. if (breakFunction && breakFunction()) {
  8478. loop.breakLoop();
  8479. break;
  8480. }
  8481. }
  8482. loop.executeNext();
  8483. }, timeout);
  8484. }
  8485. }, callback);
  8486. };
  8487. return AsyncLoop;
  8488. }());
  8489. BABYLON.AsyncLoop = AsyncLoop;
  8490. })(BABYLON || (BABYLON = {}));
  8491. //# sourceMappingURL=babylon.tools.js.map
  8492. var BABYLON;
  8493. (function (BABYLON) {
  8494. var PromiseStates;
  8495. (function (PromiseStates) {
  8496. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  8497. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  8498. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  8499. })(PromiseStates || (PromiseStates = {}));
  8500. var FulFillmentAgregator = /** @class */ (function () {
  8501. function FulFillmentAgregator() {
  8502. this.count = 0;
  8503. this.target = 0;
  8504. this.results = [];
  8505. }
  8506. return FulFillmentAgregator;
  8507. }());
  8508. var InternalPromise = /** @class */ (function () {
  8509. function InternalPromise(resolver) {
  8510. var _this = this;
  8511. this._state = PromiseStates.Pending;
  8512. this._children = new Array();
  8513. this._rejectWasConsumed = false;
  8514. if (!resolver) {
  8515. return;
  8516. }
  8517. try {
  8518. resolver(function (value) {
  8519. _this._resolve(value);
  8520. }, function (reason) {
  8521. _this._reject(reason);
  8522. });
  8523. }
  8524. catch (e) {
  8525. this._reject(e.message);
  8526. }
  8527. }
  8528. Object.defineProperty(InternalPromise.prototype, "state", {
  8529. get: function () {
  8530. return this._state;
  8531. },
  8532. enumerable: true,
  8533. configurable: true
  8534. });
  8535. Object.defineProperty(InternalPromise.prototype, "isFulfilled", {
  8536. get: function () {
  8537. return this._state === PromiseStates.Fulfilled;
  8538. },
  8539. enumerable: true,
  8540. configurable: true
  8541. });
  8542. Object.defineProperty(InternalPromise.prototype, "isRejected", {
  8543. get: function () {
  8544. return this._state === PromiseStates.Rejected;
  8545. },
  8546. enumerable: true,
  8547. configurable: true
  8548. });
  8549. Object.defineProperty(InternalPromise.prototype, "isPending", {
  8550. get: function () {
  8551. return this._state === PromiseStates.Pending;
  8552. },
  8553. enumerable: true,
  8554. configurable: true
  8555. });
  8556. InternalPromise.prototype.value = function () {
  8557. if (!this.isFulfilled) {
  8558. throw new Error("Promise is not fulfilled");
  8559. }
  8560. return this._result;
  8561. };
  8562. InternalPromise.prototype.reason = function () {
  8563. if (!this.isRejected) {
  8564. throw new Error("Promise is not rejected");
  8565. }
  8566. return this._reason;
  8567. };
  8568. InternalPromise.prototype.catch = function (onRejected) {
  8569. return this.then(undefined, onRejected);
  8570. };
  8571. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  8572. var newPromise = new InternalPromise();
  8573. newPromise._onFulfilled = onFulfilled;
  8574. newPromise._onRejected = onRejected;
  8575. // Composition
  8576. this._children.push(newPromise);
  8577. if (this._state !== PromiseStates.Pending) {
  8578. if (this._state === PromiseStates.Fulfilled || this._rejectWasConsumed) {
  8579. var returnedValue = newPromise._resolve(this._result);
  8580. if (returnedValue !== undefined && returnedValue !== null) {
  8581. if (returnedValue._state !== undefined) {
  8582. var returnedPromise = returnedValue;
  8583. newPromise._children.push(returnedPromise);
  8584. newPromise = returnedPromise;
  8585. }
  8586. else {
  8587. newPromise._result = returnedValue;
  8588. }
  8589. }
  8590. }
  8591. else {
  8592. newPromise._reject(this._reason);
  8593. }
  8594. }
  8595. return newPromise;
  8596. };
  8597. InternalPromise.prototype._moveChildren = function (children) {
  8598. this._children = children.splice(0, children.length);
  8599. if (this.isFulfilled) {
  8600. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  8601. var child = _a[_i];
  8602. child._resolve(this._result);
  8603. }
  8604. }
  8605. else if (this.isRejected) {
  8606. for (var _b = 0, _c = this._children; _b < _c.length; _b++) {
  8607. var child = _c[_b];
  8608. child._reject(this._reason);
  8609. }
  8610. }
  8611. };
  8612. InternalPromise.prototype._resolve = function (value) {
  8613. try {
  8614. this._state = PromiseStates.Fulfilled;
  8615. this._result = value;
  8616. var returnedValue = null;
  8617. if (this._onFulfilled) {
  8618. returnedValue = this._onFulfilled(value);
  8619. }
  8620. if (returnedValue !== undefined && returnedValue !== null) {
  8621. if (returnedValue._state !== undefined) {
  8622. // Transmit children
  8623. var returnedPromise = returnedValue;
  8624. returnedPromise._moveChildren(this._children);
  8625. }
  8626. }
  8627. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  8628. var child = _a[_i];
  8629. child._resolve(value);
  8630. }
  8631. return returnedValue;
  8632. }
  8633. catch (e) {
  8634. this._reject(e.message);
  8635. }
  8636. return null;
  8637. };
  8638. InternalPromise.prototype._reject = function (reason) {
  8639. this._state = PromiseStates.Rejected;
  8640. this._reason = reason;
  8641. if (this._onRejected) {
  8642. this._onRejected(reason);
  8643. this._rejectWasConsumed = true;
  8644. }
  8645. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  8646. var child = _a[_i];
  8647. if (this._rejectWasConsumed) {
  8648. child._resolve(null);
  8649. }
  8650. else {
  8651. child._reject(reason);
  8652. }
  8653. }
  8654. };
  8655. InternalPromise.resolve = function (value) {
  8656. var newPromise = new InternalPromise();
  8657. newPromise._resolve(value);
  8658. return newPromise;
  8659. };
  8660. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  8661. promise.then(function (value) {
  8662. agregator.results[index] = value;
  8663. agregator.count++;
  8664. if (agregator.count === agregator.target) {
  8665. agregator.rootPromise._resolve(agregator.results);
  8666. }
  8667. return null;
  8668. }, function (reason) {
  8669. if (!agregator.rootPromise.isRejected) {
  8670. agregator.rootPromise._reject(reason);
  8671. }
  8672. });
  8673. };
  8674. InternalPromise.all = function (promises) {
  8675. var newPromise = new InternalPromise();
  8676. var agregator = new FulFillmentAgregator();
  8677. agregator.target = promises.length;
  8678. agregator.rootPromise = newPromise;
  8679. for (var index = 0; index < promises.length; index++) {
  8680. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  8681. }
  8682. return newPromise;
  8683. };
  8684. return InternalPromise;
  8685. }());
  8686. /**
  8687. * Helper class that provides a small promise polyfill
  8688. */
  8689. var PromisePolyfill = /** @class */ (function () {
  8690. function PromisePolyfill() {
  8691. }
  8692. /**
  8693. * Static function used to check if the polyfill is required
  8694. * If this is the case then the function will inject the polyfill to window.Promise
  8695. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  8696. */
  8697. PromisePolyfill.Apply = function (force) {
  8698. if (force === void 0) { force = false; }
  8699. if (force || typeof Promise === 'undefined') {
  8700. var root = window;
  8701. root.Promise = InternalPromise;
  8702. }
  8703. };
  8704. return PromisePolyfill;
  8705. }());
  8706. BABYLON.PromisePolyfill = PromisePolyfill;
  8707. })(BABYLON || (BABYLON = {}));
  8708. //# sourceMappingURL=babylon.promise.js.map
  8709. var BABYLON;
  8710. (function (BABYLON) {
  8711. var _AlphaState = /** @class */ (function () {
  8712. /**
  8713. * Initializes the state.
  8714. */
  8715. function _AlphaState() {
  8716. this._isAlphaBlendDirty = false;
  8717. this._isBlendFunctionParametersDirty = false;
  8718. this._isBlendEquationParametersDirty = false;
  8719. this._isBlendConstantsDirty = false;
  8720. this._alphaBlend = false;
  8721. this._blendFunctionParameters = new Array(4);
  8722. this._blendEquationParameters = new Array(2);
  8723. this._blendConstants = new Array(4);
  8724. this.reset();
  8725. }
  8726. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  8727. get: function () {
  8728. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  8729. },
  8730. enumerable: true,
  8731. configurable: true
  8732. });
  8733. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  8734. get: function () {
  8735. return this._alphaBlend;
  8736. },
  8737. set: function (value) {
  8738. if (this._alphaBlend === value) {
  8739. return;
  8740. }
  8741. this._alphaBlend = value;
  8742. this._isAlphaBlendDirty = true;
  8743. },
  8744. enumerable: true,
  8745. configurable: true
  8746. });
  8747. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  8748. if (this._blendConstants[0] === r &&
  8749. this._blendConstants[1] === g &&
  8750. this._blendConstants[2] === b &&
  8751. this._blendConstants[3] === a) {
  8752. return;
  8753. }
  8754. this._blendConstants[0] = r;
  8755. this._blendConstants[1] = g;
  8756. this._blendConstants[2] = b;
  8757. this._blendConstants[3] = a;
  8758. this._isBlendConstantsDirty = true;
  8759. };
  8760. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  8761. if (this._blendFunctionParameters[0] === value0 &&
  8762. this._blendFunctionParameters[1] === value1 &&
  8763. this._blendFunctionParameters[2] === value2 &&
  8764. this._blendFunctionParameters[3] === value3) {
  8765. return;
  8766. }
  8767. this._blendFunctionParameters[0] = value0;
  8768. this._blendFunctionParameters[1] = value1;
  8769. this._blendFunctionParameters[2] = value2;
  8770. this._blendFunctionParameters[3] = value3;
  8771. this._isBlendFunctionParametersDirty = true;
  8772. };
  8773. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  8774. if (this._blendEquationParameters[0] === rgb &&
  8775. this._blendEquationParameters[1] === alpha) {
  8776. return;
  8777. }
  8778. this._blendEquationParameters[0] = rgb;
  8779. this._blendEquationParameters[1] = alpha;
  8780. this._isBlendEquationParametersDirty = true;
  8781. };
  8782. _AlphaState.prototype.reset = function () {
  8783. this._alphaBlend = false;
  8784. this._blendFunctionParameters[0] = null;
  8785. this._blendFunctionParameters[1] = null;
  8786. this._blendFunctionParameters[2] = null;
  8787. this._blendFunctionParameters[3] = null;
  8788. this._blendEquationParameters[0] = null;
  8789. this._blendEquationParameters[1] = null;
  8790. this._blendConstants[0] = null;
  8791. this._blendConstants[1] = null;
  8792. this._blendConstants[2] = null;
  8793. this._blendConstants[3] = null;
  8794. this._isAlphaBlendDirty = true;
  8795. this._isBlendFunctionParametersDirty = false;
  8796. this._isBlendEquationParametersDirty = false;
  8797. this._isBlendConstantsDirty = false;
  8798. };
  8799. _AlphaState.prototype.apply = function (gl) {
  8800. if (!this.isDirty) {
  8801. return;
  8802. }
  8803. // Alpha blend
  8804. if (this._isAlphaBlendDirty) {
  8805. if (this._alphaBlend) {
  8806. gl.enable(gl.BLEND);
  8807. }
  8808. else {
  8809. gl.disable(gl.BLEND);
  8810. }
  8811. this._isAlphaBlendDirty = false;
  8812. }
  8813. // Alpha function
  8814. if (this._isBlendFunctionParametersDirty) {
  8815. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  8816. this._isBlendFunctionParametersDirty = false;
  8817. }
  8818. // Alpha equation
  8819. if (this._isBlendEquationParametersDirty) {
  8820. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  8821. this._isBlendEquationParametersDirty = false;
  8822. }
  8823. // Constants
  8824. if (this._isBlendConstantsDirty) {
  8825. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  8826. this._isBlendConstantsDirty = false;
  8827. }
  8828. };
  8829. return _AlphaState;
  8830. }());
  8831. BABYLON._AlphaState = _AlphaState;
  8832. })(BABYLON || (BABYLON = {}));
  8833. //# sourceMappingURL=babylon.alphaCullingState.js.map
  8834. var BABYLON;
  8835. (function (BABYLON) {
  8836. var _DepthCullingState = /** @class */ (function () {
  8837. /**
  8838. * Initializes the state.
  8839. */
  8840. function _DepthCullingState() {
  8841. this._isDepthTestDirty = false;
  8842. this._isDepthMaskDirty = false;
  8843. this._isDepthFuncDirty = false;
  8844. this._isCullFaceDirty = false;
  8845. this._isCullDirty = false;
  8846. this._isZOffsetDirty = false;
  8847. this._isFrontFaceDirty = false;
  8848. this.reset();
  8849. }
  8850. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  8851. get: function () {
  8852. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  8853. },
  8854. enumerable: true,
  8855. configurable: true
  8856. });
  8857. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  8858. get: function () {
  8859. return this._zOffset;
  8860. },
  8861. set: function (value) {
  8862. if (this._zOffset === value) {
  8863. return;
  8864. }
  8865. this._zOffset = value;
  8866. this._isZOffsetDirty = true;
  8867. },
  8868. enumerable: true,
  8869. configurable: true
  8870. });
  8871. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  8872. get: function () {
  8873. return this._cullFace;
  8874. },
  8875. set: function (value) {
  8876. if (this._cullFace === value) {
  8877. return;
  8878. }
  8879. this._cullFace = value;
  8880. this._isCullFaceDirty = true;
  8881. },
  8882. enumerable: true,
  8883. configurable: true
  8884. });
  8885. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  8886. get: function () {
  8887. return this._cull;
  8888. },
  8889. set: function (value) {
  8890. if (this._cull === value) {
  8891. return;
  8892. }
  8893. this._cull = value;
  8894. this._isCullDirty = true;
  8895. },
  8896. enumerable: true,
  8897. configurable: true
  8898. });
  8899. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  8900. get: function () {
  8901. return this._depthFunc;
  8902. },
  8903. set: function (value) {
  8904. if (this._depthFunc === value) {
  8905. return;
  8906. }
  8907. this._depthFunc = value;
  8908. this._isDepthFuncDirty = true;
  8909. },
  8910. enumerable: true,
  8911. configurable: true
  8912. });
  8913. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  8914. get: function () {
  8915. return this._depthMask;
  8916. },
  8917. set: function (value) {
  8918. if (this._depthMask === value) {
  8919. return;
  8920. }
  8921. this._depthMask = value;
  8922. this._isDepthMaskDirty = true;
  8923. },
  8924. enumerable: true,
  8925. configurable: true
  8926. });
  8927. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  8928. get: function () {
  8929. return this._depthTest;
  8930. },
  8931. set: function (value) {
  8932. if (this._depthTest === value) {
  8933. return;
  8934. }
  8935. this._depthTest = value;
  8936. this._isDepthTestDirty = true;
  8937. },
  8938. enumerable: true,
  8939. configurable: true
  8940. });
  8941. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  8942. get: function () {
  8943. return this._frontFace;
  8944. },
  8945. set: function (value) {
  8946. if (this._frontFace === value) {
  8947. return;
  8948. }
  8949. this._frontFace = value;
  8950. this._isFrontFaceDirty = true;
  8951. },
  8952. enumerable: true,
  8953. configurable: true
  8954. });
  8955. _DepthCullingState.prototype.reset = function () {
  8956. this._depthMask = true;
  8957. this._depthTest = true;
  8958. this._depthFunc = null;
  8959. this._cullFace = null;
  8960. this._cull = null;
  8961. this._zOffset = 0;
  8962. this._frontFace = null;
  8963. this._isDepthTestDirty = true;
  8964. this._isDepthMaskDirty = true;
  8965. this._isDepthFuncDirty = false;
  8966. this._isCullFaceDirty = false;
  8967. this._isCullDirty = false;
  8968. this._isZOffsetDirty = false;
  8969. this._isFrontFaceDirty = false;
  8970. };
  8971. _DepthCullingState.prototype.apply = function (gl) {
  8972. if (!this.isDirty) {
  8973. return;
  8974. }
  8975. // Cull
  8976. if (this._isCullDirty) {
  8977. if (this.cull) {
  8978. gl.enable(gl.CULL_FACE);
  8979. }
  8980. else {
  8981. gl.disable(gl.CULL_FACE);
  8982. }
  8983. this._isCullDirty = false;
  8984. }
  8985. // Cull face
  8986. if (this._isCullFaceDirty) {
  8987. gl.cullFace(this.cullFace);
  8988. this._isCullFaceDirty = false;
  8989. }
  8990. // Depth mask
  8991. if (this._isDepthMaskDirty) {
  8992. gl.depthMask(this.depthMask);
  8993. this._isDepthMaskDirty = false;
  8994. }
  8995. // Depth test
  8996. if (this._isDepthTestDirty) {
  8997. if (this.depthTest) {
  8998. gl.enable(gl.DEPTH_TEST);
  8999. }
  9000. else {
  9001. gl.disable(gl.DEPTH_TEST);
  9002. }
  9003. this._isDepthTestDirty = false;
  9004. }
  9005. // Depth func
  9006. if (this._isDepthFuncDirty) {
  9007. gl.depthFunc(this.depthFunc);
  9008. this._isDepthFuncDirty = false;
  9009. }
  9010. // zOffset
  9011. if (this._isZOffsetDirty) {
  9012. if (this.zOffset) {
  9013. gl.enable(gl.POLYGON_OFFSET_FILL);
  9014. gl.polygonOffset(this.zOffset, 0);
  9015. }
  9016. else {
  9017. gl.disable(gl.POLYGON_OFFSET_FILL);
  9018. }
  9019. this._isZOffsetDirty = false;
  9020. }
  9021. // Front face
  9022. if (this._isFrontFaceDirty) {
  9023. gl.frontFace(this.frontFace);
  9024. this._isFrontFaceDirty = false;
  9025. }
  9026. };
  9027. return _DepthCullingState;
  9028. }());
  9029. BABYLON._DepthCullingState = _DepthCullingState;
  9030. })(BABYLON || (BABYLON = {}));
  9031. //# sourceMappingURL=babylon.depthCullingState.js.map
  9032. var BABYLON;
  9033. (function (BABYLON) {
  9034. var _StencilState = /** @class */ (function () {
  9035. function _StencilState() {
  9036. this._isStencilTestDirty = false;
  9037. this._isStencilMaskDirty = false;
  9038. this._isStencilFuncDirty = false;
  9039. this._isStencilOpDirty = false;
  9040. this.reset();
  9041. }
  9042. Object.defineProperty(_StencilState.prototype, "isDirty", {
  9043. get: function () {
  9044. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  9045. },
  9046. enumerable: true,
  9047. configurable: true
  9048. });
  9049. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  9050. get: function () {
  9051. return this._stencilFunc;
  9052. },
  9053. set: function (value) {
  9054. if (this._stencilFunc === value) {
  9055. return;
  9056. }
  9057. this._stencilFunc = value;
  9058. this._isStencilFuncDirty = true;
  9059. },
  9060. enumerable: true,
  9061. configurable: true
  9062. });
  9063. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  9064. get: function () {
  9065. return this._stencilFuncRef;
  9066. },
  9067. set: function (value) {
  9068. if (this._stencilFuncRef === value) {
  9069. return;
  9070. }
  9071. this._stencilFuncRef = value;
  9072. this._isStencilFuncDirty = true;
  9073. },
  9074. enumerable: true,
  9075. configurable: true
  9076. });
  9077. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  9078. get: function () {
  9079. return this._stencilFuncMask;
  9080. },
  9081. set: function (value) {
  9082. if (this._stencilFuncMask === value) {
  9083. return;
  9084. }
  9085. this._stencilFuncMask = value;
  9086. this._isStencilFuncDirty = true;
  9087. },
  9088. enumerable: true,
  9089. configurable: true
  9090. });
  9091. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  9092. get: function () {
  9093. return this._stencilOpStencilFail;
  9094. },
  9095. set: function (value) {
  9096. if (this._stencilOpStencilFail === value) {
  9097. return;
  9098. }
  9099. this._stencilOpStencilFail = value;
  9100. this._isStencilOpDirty = true;
  9101. },
  9102. enumerable: true,
  9103. configurable: true
  9104. });
  9105. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  9106. get: function () {
  9107. return this._stencilOpDepthFail;
  9108. },
  9109. set: function (value) {
  9110. if (this._stencilOpDepthFail === value) {
  9111. return;
  9112. }
  9113. this._stencilOpDepthFail = value;
  9114. this._isStencilOpDirty = true;
  9115. },
  9116. enumerable: true,
  9117. configurable: true
  9118. });
  9119. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  9120. get: function () {
  9121. return this._stencilOpStencilDepthPass;
  9122. },
  9123. set: function (value) {
  9124. if (this._stencilOpStencilDepthPass === value) {
  9125. return;
  9126. }
  9127. this._stencilOpStencilDepthPass = value;
  9128. this._isStencilOpDirty = true;
  9129. },
  9130. enumerable: true,
  9131. configurable: true
  9132. });
  9133. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  9134. get: function () {
  9135. return this._stencilMask;
  9136. },
  9137. set: function (value) {
  9138. if (this._stencilMask === value) {
  9139. return;
  9140. }
  9141. this._stencilMask = value;
  9142. this._isStencilMaskDirty = true;
  9143. },
  9144. enumerable: true,
  9145. configurable: true
  9146. });
  9147. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  9148. get: function () {
  9149. return this._stencilTest;
  9150. },
  9151. set: function (value) {
  9152. if (this._stencilTest === value) {
  9153. return;
  9154. }
  9155. this._stencilTest = value;
  9156. this._isStencilTestDirty = true;
  9157. },
  9158. enumerable: true,
  9159. configurable: true
  9160. });
  9161. _StencilState.prototype.reset = function () {
  9162. this._stencilTest = false;
  9163. this._stencilMask = 0xFF;
  9164. this._stencilFunc = BABYLON.Engine.ALWAYS;
  9165. this._stencilFuncRef = 1;
  9166. this._stencilFuncMask = 0xFF;
  9167. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  9168. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  9169. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  9170. this._isStencilTestDirty = true;
  9171. this._isStencilMaskDirty = true;
  9172. this._isStencilFuncDirty = true;
  9173. this._isStencilOpDirty = true;
  9174. };
  9175. _StencilState.prototype.apply = function (gl) {
  9176. if (!this.isDirty) {
  9177. return;
  9178. }
  9179. // Stencil test
  9180. if (this._isStencilTestDirty) {
  9181. if (this.stencilTest) {
  9182. gl.enable(gl.STENCIL_TEST);
  9183. }
  9184. else {
  9185. gl.disable(gl.STENCIL_TEST);
  9186. }
  9187. this._isStencilTestDirty = false;
  9188. }
  9189. // Stencil mask
  9190. if (this._isStencilMaskDirty) {
  9191. gl.stencilMask(this.stencilMask);
  9192. this._isStencilMaskDirty = false;
  9193. }
  9194. // Stencil func
  9195. if (this._isStencilFuncDirty) {
  9196. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  9197. this._isStencilFuncDirty = false;
  9198. }
  9199. // Stencil op
  9200. if (this._isStencilOpDirty) {
  9201. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  9202. this._isStencilOpDirty = false;
  9203. }
  9204. };
  9205. return _StencilState;
  9206. }());
  9207. BABYLON._StencilState = _StencilState;
  9208. })(BABYLON || (BABYLON = {}));
  9209. //# sourceMappingURL=babylon.stencilState.js.map
  9210. var BABYLON;
  9211. (function (BABYLON) {
  9212. var compileShader = function (gl, source, type, defines, shaderVersion) {
  9213. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  9214. };
  9215. var compileRawShader = function (gl, source, type) {
  9216. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  9217. gl.shaderSource(shader, source);
  9218. gl.compileShader(shader);
  9219. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  9220. var log = gl.getShaderInfoLog(shader);
  9221. if (log) {
  9222. throw new Error(log);
  9223. }
  9224. }
  9225. if (!shader) {
  9226. throw new Error("Something went wrong while compile the shader.");
  9227. }
  9228. return shader;
  9229. };
  9230. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  9231. var magFilter = gl.NEAREST;
  9232. var minFilter = gl.NEAREST;
  9233. switch (samplingMode) {
  9234. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  9235. magFilter = gl.LINEAR;
  9236. if (generateMipMaps) {
  9237. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  9238. }
  9239. else {
  9240. minFilter = gl.LINEAR;
  9241. }
  9242. break;
  9243. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  9244. magFilter = gl.LINEAR;
  9245. if (generateMipMaps) {
  9246. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  9247. }
  9248. else {
  9249. minFilter = gl.LINEAR;
  9250. }
  9251. break;
  9252. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  9253. magFilter = gl.NEAREST;
  9254. if (generateMipMaps) {
  9255. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  9256. }
  9257. else {
  9258. minFilter = gl.NEAREST;
  9259. }
  9260. break;
  9261. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  9262. magFilter = gl.NEAREST;
  9263. if (generateMipMaps) {
  9264. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  9265. }
  9266. else {
  9267. minFilter = gl.NEAREST;
  9268. }
  9269. break;
  9270. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  9271. magFilter = gl.NEAREST;
  9272. if (generateMipMaps) {
  9273. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  9274. }
  9275. else {
  9276. minFilter = gl.LINEAR;
  9277. }
  9278. break;
  9279. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  9280. magFilter = gl.NEAREST;
  9281. if (generateMipMaps) {
  9282. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  9283. }
  9284. else {
  9285. minFilter = gl.LINEAR;
  9286. }
  9287. break;
  9288. case BABYLON.Texture.NEAREST_LINEAR:
  9289. magFilter = gl.NEAREST;
  9290. minFilter = gl.LINEAR;
  9291. break;
  9292. case BABYLON.Texture.NEAREST_NEAREST:
  9293. magFilter = gl.NEAREST;
  9294. minFilter = gl.NEAREST;
  9295. break;
  9296. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  9297. magFilter = gl.LINEAR;
  9298. if (generateMipMaps) {
  9299. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  9300. }
  9301. else {
  9302. minFilter = gl.NEAREST;
  9303. }
  9304. break;
  9305. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  9306. magFilter = gl.LINEAR;
  9307. if (generateMipMaps) {
  9308. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  9309. }
  9310. else {
  9311. minFilter = gl.NEAREST;
  9312. }
  9313. break;
  9314. case BABYLON.Texture.LINEAR_LINEAR:
  9315. magFilter = gl.LINEAR;
  9316. minFilter = gl.LINEAR;
  9317. break;
  9318. case BABYLON.Texture.LINEAR_NEAREST:
  9319. magFilter = gl.LINEAR;
  9320. minFilter = gl.NEAREST;
  9321. break;
  9322. }
  9323. return {
  9324. min: minFilter,
  9325. mag: magFilter
  9326. };
  9327. };
  9328. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  9329. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  9330. var img;
  9331. var onload = function () {
  9332. loadedImages[index] = img;
  9333. loadedImages._internalCount++;
  9334. if (scene) {
  9335. scene._removePendingData(img);
  9336. }
  9337. if (loadedImages._internalCount === 6) {
  9338. onfinish(loadedImages);
  9339. }
  9340. };
  9341. var onerror = function (message, exception) {
  9342. if (scene) {
  9343. scene._removePendingData(img);
  9344. }
  9345. if (onErrorCallBack) {
  9346. onErrorCallBack(message, exception);
  9347. }
  9348. };
  9349. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  9350. if (scene) {
  9351. scene._addPendingData(img);
  9352. }
  9353. };
  9354. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  9355. if (onError === void 0) { onError = null; }
  9356. var loadedImages = [];
  9357. loadedImages._internalCount = 0;
  9358. for (var index = 0; index < 6; index++) {
  9359. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  9360. }
  9361. };
  9362. var BufferPointer = /** @class */ (function () {
  9363. function BufferPointer() {
  9364. }
  9365. return BufferPointer;
  9366. }());
  9367. var InstancingAttributeInfo = /** @class */ (function () {
  9368. function InstancingAttributeInfo() {
  9369. }
  9370. return InstancingAttributeInfo;
  9371. }());
  9372. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  9373. /**
  9374. * Define options used to create a render target texture
  9375. */
  9376. var RenderTargetCreationOptions = /** @class */ (function () {
  9377. function RenderTargetCreationOptions() {
  9378. }
  9379. return RenderTargetCreationOptions;
  9380. }());
  9381. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  9382. /**
  9383. * Regroup several parameters relative to the browser in use
  9384. */
  9385. var EngineCapabilities = /** @class */ (function () {
  9386. function EngineCapabilities() {
  9387. }
  9388. return EngineCapabilities;
  9389. }());
  9390. BABYLON.EngineCapabilities = EngineCapabilities;
  9391. /**
  9392. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  9393. */
  9394. var Engine = /** @class */ (function () {
  9395. /**
  9396. * @constructor
  9397. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  9398. * @param antialias defines enable antialiasing (default: false)
  9399. * @param options defines further options to be sent to the getContext() function
  9400. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  9401. */
  9402. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  9403. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  9404. var _this = this;
  9405. // Public members
  9406. this.forcePOTTextures = false;
  9407. this.isFullscreen = false;
  9408. this.isPointerLock = false;
  9409. this.cullBackFaces = true;
  9410. this.renderEvenInBackground = true;
  9411. this.preventCacheWipeBetweenFrames = false;
  9412. // To enable/disable IDB support and avoid XHR on .manifest
  9413. this.enableOfflineSupport = false;
  9414. this.scenes = new Array();
  9415. this.postProcesses = new Array();
  9416. // Observables
  9417. /**
  9418. * Observable event triggered each time the rendering canvas is resized
  9419. */
  9420. this.onResizeObservable = new BABYLON.Observable();
  9421. /**
  9422. * Observable event triggered each time the canvas loses focus
  9423. */
  9424. this.onCanvasBlurObservable = new BABYLON.Observable();
  9425. /**
  9426. * Observable event triggered each time the canvas gains focus
  9427. */
  9428. this.onCanvasFocusObservable = new BABYLON.Observable();
  9429. /**
  9430. * Observable event triggered each time the canvas receives pointerout event
  9431. */
  9432. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  9433. /**
  9434. * Observable event triggered before each texture is initialized
  9435. */
  9436. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  9437. //WebVR
  9438. this._vrDisplay = undefined;
  9439. this._vrSupported = false;
  9440. this._vrExclusivePointerMode = false;
  9441. // Uniform buffers list
  9442. this.disableUniformBuffers = false;
  9443. this._uniformBuffers = new Array();
  9444. // Observables
  9445. /**
  9446. * Observable raised when the engine begins a new frame
  9447. */
  9448. this.onBeginFrameObservable = new BABYLON.Observable();
  9449. /**
  9450. * Observable raised when the engine ends the current frame
  9451. */
  9452. this.onEndFrameObservable = new BABYLON.Observable();
  9453. /**
  9454. * Observable raised when the engine is about to compile a shader
  9455. */
  9456. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  9457. /**
  9458. * Observable raised when the engine has jsut compiled a shader
  9459. */
  9460. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  9461. this._windowIsBackground = false;
  9462. this._webGLVersion = 1.0;
  9463. this._badOS = false;
  9464. this._badDesktopOS = false;
  9465. /**
  9466. * Gets or sets a value indicating if we want to disable texture binding optmization.
  9467. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  9468. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  9469. */
  9470. this.disableTextureBindingOptimization = false;
  9471. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  9472. this.onVRRequestPresentComplete = new BABYLON.Observable();
  9473. this.onVRRequestPresentStart = new BABYLON.Observable();
  9474. this._colorWrite = true;
  9475. this._drawCalls = new BABYLON.PerfCounter();
  9476. this._textureCollisions = new BABYLON.PerfCounter();
  9477. this._renderingQueueLaunched = false;
  9478. this._activeRenderLoops = new Array();
  9479. // Deterministic lockstepMaxSteps
  9480. this._deterministicLockstep = false;
  9481. this._lockstepMaxSteps = 4;
  9482. // Lost context
  9483. this.onContextLostObservable = new BABYLON.Observable();
  9484. this.onContextRestoredObservable = new BABYLON.Observable();
  9485. this._contextWasLost = false;
  9486. this._doNotHandleContextLost = false;
  9487. // FPS
  9488. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  9489. this._fps = 60;
  9490. this._deltaTime = 0;
  9491. /**
  9492. * Turn this value on if you want to pause FPS computation when in background
  9493. */
  9494. this.disablePerformanceMonitorInBackground = false;
  9495. // States
  9496. this._depthCullingState = new BABYLON._DepthCullingState();
  9497. this._stencilState = new BABYLON._StencilState();
  9498. this._alphaState = new BABYLON._AlphaState();
  9499. this._alphaMode = Engine.ALPHA_DISABLE;
  9500. // Cache
  9501. this._internalTexturesCache = new Array();
  9502. this._activeChannel = 0;
  9503. this._currentTextureChannel = -1;
  9504. this._boundTexturesCache = {};
  9505. this._compiledEffects = {};
  9506. this._vertexAttribArraysEnabled = [];
  9507. this._uintIndicesCurrentlySet = false;
  9508. this._currentBoundBuffer = new Array();
  9509. this._currentBufferPointers = new Array();
  9510. this._currentInstanceLocations = new Array();
  9511. this._currentInstanceBuffers = new Array();
  9512. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  9513. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  9514. this._vaoRecordInProgress = false;
  9515. this._mustWipeVertexAttributes = false;
  9516. this._nextFreeTextureSlots = new Array();
  9517. this._maxSimultaneousTextures = 0;
  9518. this._activeRequests = new Array();
  9519. // Hardware supported Compressed Textures
  9520. this._texturesSupported = new Array();
  9521. this._onVRFullScreenTriggered = function () {
  9522. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  9523. //get the old size before we change
  9524. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  9525. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  9526. //get the width and height, change the render size
  9527. var leftEye = _this._vrDisplay.getEyeParameters('left');
  9528. _this.setHardwareScalingLevel(1);
  9529. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  9530. }
  9531. else {
  9532. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  9533. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  9534. }
  9535. };
  9536. this._boundUniforms = {};
  9537. // Register promises
  9538. BABYLON.PromisePolyfill.Apply();
  9539. var canvas = null;
  9540. Engine.Instances.push(this);
  9541. if (!canvasOrContext) {
  9542. return;
  9543. }
  9544. options = options || {};
  9545. if (canvasOrContext.getContext) {
  9546. canvas = canvasOrContext;
  9547. this._renderingCanvas = canvas;
  9548. if (antialias != null) {
  9549. options.antialias = antialias;
  9550. }
  9551. if (options.deterministicLockstep === undefined) {
  9552. options.deterministicLockstep = false;
  9553. }
  9554. if (options.lockstepMaxSteps === undefined) {
  9555. options.lockstepMaxSteps = 4;
  9556. }
  9557. if (options.preserveDrawingBuffer === undefined) {
  9558. options.preserveDrawingBuffer = false;
  9559. }
  9560. if (options.audioEngine === undefined) {
  9561. options.audioEngine = true;
  9562. }
  9563. if (options.stencil === undefined) {
  9564. options.stencil = true;
  9565. }
  9566. this._deterministicLockstep = options.deterministicLockstep;
  9567. this._lockstepMaxSteps = options.lockstepMaxSteps;
  9568. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  9569. // Exceptions
  9570. if (navigator && navigator.userAgent) {
  9571. var ua = navigator.userAgent;
  9572. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  9573. var exception = _a[_i];
  9574. var key = exception.key;
  9575. var targets = exception.targets;
  9576. if (ua.indexOf(key) > -1) {
  9577. if (exception.capture && exception.captureConstraint) {
  9578. var capture = exception.capture;
  9579. var constraint = exception.captureConstraint;
  9580. var regex = new RegExp(capture);
  9581. var matches = regex.exec(ua);
  9582. if (matches && matches.length > 0) {
  9583. var capturedValue = parseInt(matches[matches.length - 1]);
  9584. if (capturedValue >= constraint) {
  9585. continue;
  9586. }
  9587. }
  9588. }
  9589. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  9590. var target = targets_1[_b];
  9591. switch (target) {
  9592. case "uniformBuffer":
  9593. this.disableUniformBuffers = true;
  9594. break;
  9595. case "textureBindingOptimization":
  9596. this.disableTextureBindingOptimization = true;
  9597. break;
  9598. }
  9599. }
  9600. break;
  9601. }
  9602. }
  9603. }
  9604. // GL
  9605. if (!options.disableWebGL2Support) {
  9606. try {
  9607. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  9608. if (this._gl) {
  9609. this._webGLVersion = 2.0;
  9610. }
  9611. }
  9612. catch (e) {
  9613. // Do nothing
  9614. }
  9615. }
  9616. if (!this._gl) {
  9617. if (!canvas) {
  9618. throw new Error("The provided canvas is null or undefined.");
  9619. }
  9620. try {
  9621. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  9622. }
  9623. catch (e) {
  9624. throw new Error("WebGL not supported");
  9625. }
  9626. }
  9627. if (!this._gl) {
  9628. throw new Error("WebGL not supported");
  9629. }
  9630. this._onCanvasFocus = function () {
  9631. _this.onCanvasFocusObservable.notifyObservers(_this);
  9632. };
  9633. this._onCanvasBlur = function () {
  9634. _this.onCanvasBlurObservable.notifyObservers(_this);
  9635. };
  9636. canvas.addEventListener("focus", this._onCanvasFocus);
  9637. canvas.addEventListener("blur", this._onCanvasBlur);
  9638. this._onBlur = function () {
  9639. if (_this.disablePerformanceMonitorInBackground) {
  9640. _this._performanceMonitor.disable();
  9641. }
  9642. _this._windowIsBackground = true;
  9643. };
  9644. this._onFocus = function () {
  9645. if (_this.disablePerformanceMonitorInBackground) {
  9646. _this._performanceMonitor.enable();
  9647. }
  9648. _this._windowIsBackground = false;
  9649. };
  9650. this._onCanvasPointerOut = function () {
  9651. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  9652. };
  9653. window.addEventListener("blur", this._onBlur);
  9654. window.addEventListener("focus", this._onFocus);
  9655. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  9656. // Context lost
  9657. if (!this._doNotHandleContextLost) {
  9658. this._onContextLost = function (evt) {
  9659. evt.preventDefault();
  9660. _this._contextWasLost = true;
  9661. BABYLON.Tools.Warn("WebGL context lost.");
  9662. _this.onContextLostObservable.notifyObservers(_this);
  9663. };
  9664. this._onContextRestored = function (evt) {
  9665. // Adding a timeout to avoid race condition at browser level
  9666. setTimeout(function () {
  9667. // Rebuild gl context
  9668. _this._initGLContext();
  9669. // Rebuild effects
  9670. _this._rebuildEffects();
  9671. // Rebuild textures
  9672. _this._rebuildInternalTextures();
  9673. // Rebuild buffers
  9674. _this._rebuildBuffers();
  9675. // Cache
  9676. _this.wipeCaches(true);
  9677. BABYLON.Tools.Warn("WebGL context successfully restored.");
  9678. _this.onContextRestoredObservable.notifyObservers(_this);
  9679. _this._contextWasLost = false;
  9680. }, 0);
  9681. };
  9682. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  9683. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  9684. }
  9685. }
  9686. else {
  9687. this._gl = canvasOrContext;
  9688. this._renderingCanvas = this._gl.canvas;
  9689. if (this._gl.renderbufferStorageMultisample) {
  9690. this._webGLVersion = 2.0;
  9691. }
  9692. options.stencil = this._gl.getContextAttributes().stencil;
  9693. }
  9694. // Viewport
  9695. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  9696. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  9697. this.resize();
  9698. this._isStencilEnable = options.stencil ? true : false;
  9699. this._initGLContext();
  9700. if (canvas) {
  9701. // Fullscreen
  9702. this._onFullscreenChange = function () {
  9703. if (document.fullscreen !== undefined) {
  9704. _this.isFullscreen = document.fullscreen;
  9705. }
  9706. else if (document.mozFullScreen !== undefined) {
  9707. _this.isFullscreen = document.mozFullScreen;
  9708. }
  9709. else if (document.webkitIsFullScreen !== undefined) {
  9710. _this.isFullscreen = document.webkitIsFullScreen;
  9711. }
  9712. else if (document.msIsFullScreen !== undefined) {
  9713. _this.isFullscreen = document.msIsFullScreen;
  9714. }
  9715. // Pointer lock
  9716. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  9717. canvas.requestPointerLock = canvas.requestPointerLock ||
  9718. canvas.msRequestPointerLock ||
  9719. canvas.mozRequestPointerLock ||
  9720. canvas.webkitRequestPointerLock;
  9721. if (canvas.requestPointerLock) {
  9722. canvas.requestPointerLock();
  9723. }
  9724. }
  9725. };
  9726. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  9727. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  9728. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  9729. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  9730. // Pointer lock
  9731. this._onPointerLockChange = function () {
  9732. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  9733. document.webkitPointerLockElement === canvas ||
  9734. document.msPointerLockElement === canvas ||
  9735. document.pointerLockElement === canvas);
  9736. };
  9737. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  9738. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  9739. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  9740. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  9741. this._onVRDisplayPointerRestricted = function () {
  9742. if (canvas) {
  9743. canvas.requestPointerLock();
  9744. }
  9745. };
  9746. this._onVRDisplayPointerUnrestricted = function () {
  9747. document.exitPointerLock();
  9748. };
  9749. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  9750. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  9751. }
  9752. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  9753. Engine.audioEngine = new BABYLON.AudioEngine();
  9754. }
  9755. // Prepare buffer pointers
  9756. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  9757. this._currentBufferPointers[i] = new BufferPointer();
  9758. }
  9759. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  9760. // Load WebVR Devices
  9761. if (options.autoEnableWebVR) {
  9762. this.initWebVR();
  9763. }
  9764. // Detect if we are running on a faulty buggy OS.
  9765. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  9766. // Detect if we are running on a faulty buggy desktop OS.
  9767. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  9768. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  9769. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  9770. }
  9771. Object.defineProperty(Engine, "LastCreatedEngine", {
  9772. get: function () {
  9773. if (Engine.Instances.length === 0) {
  9774. return null;
  9775. }
  9776. return Engine.Instances[Engine.Instances.length - 1];
  9777. },
  9778. enumerable: true,
  9779. configurable: true
  9780. });
  9781. Object.defineProperty(Engine, "LastCreatedScene", {
  9782. get: function () {
  9783. var lastCreatedEngine = Engine.LastCreatedEngine;
  9784. if (!lastCreatedEngine) {
  9785. return null;
  9786. }
  9787. if (lastCreatedEngine.scenes.length === 0) {
  9788. return null;
  9789. }
  9790. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  9791. },
  9792. enumerable: true,
  9793. configurable: true
  9794. });
  9795. /**
  9796. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  9797. */
  9798. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  9799. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  9800. var engine = Engine.Instances[engineIndex];
  9801. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  9802. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  9803. }
  9804. }
  9805. };
  9806. Object.defineProperty(Engine, "NEVER", {
  9807. get: function () {
  9808. return Engine._NEVER;
  9809. },
  9810. enumerable: true,
  9811. configurable: true
  9812. });
  9813. Object.defineProperty(Engine, "ALWAYS", {
  9814. get: function () {
  9815. return Engine._ALWAYS;
  9816. },
  9817. enumerable: true,
  9818. configurable: true
  9819. });
  9820. Object.defineProperty(Engine, "LESS", {
  9821. get: function () {
  9822. return Engine._LESS;
  9823. },
  9824. enumerable: true,
  9825. configurable: true
  9826. });
  9827. Object.defineProperty(Engine, "EQUAL", {
  9828. get: function () {
  9829. return Engine._EQUAL;
  9830. },
  9831. enumerable: true,
  9832. configurable: true
  9833. });
  9834. Object.defineProperty(Engine, "LEQUAL", {
  9835. get: function () {
  9836. return Engine._LEQUAL;
  9837. },
  9838. enumerable: true,
  9839. configurable: true
  9840. });
  9841. Object.defineProperty(Engine, "GREATER", {
  9842. get: function () {
  9843. return Engine._GREATER;
  9844. },
  9845. enumerable: true,
  9846. configurable: true
  9847. });
  9848. Object.defineProperty(Engine, "GEQUAL", {
  9849. get: function () {
  9850. return Engine._GEQUAL;
  9851. },
  9852. enumerable: true,
  9853. configurable: true
  9854. });
  9855. Object.defineProperty(Engine, "NOTEQUAL", {
  9856. get: function () {
  9857. return Engine._NOTEQUAL;
  9858. },
  9859. enumerable: true,
  9860. configurable: true
  9861. });
  9862. Object.defineProperty(Engine, "KEEP", {
  9863. get: function () {
  9864. return Engine._KEEP;
  9865. },
  9866. enumerable: true,
  9867. configurable: true
  9868. });
  9869. Object.defineProperty(Engine, "REPLACE", {
  9870. get: function () {
  9871. return Engine._REPLACE;
  9872. },
  9873. enumerable: true,
  9874. configurable: true
  9875. });
  9876. Object.defineProperty(Engine, "INCR", {
  9877. get: function () {
  9878. return Engine._INCR;
  9879. },
  9880. enumerable: true,
  9881. configurable: true
  9882. });
  9883. Object.defineProperty(Engine, "DECR", {
  9884. get: function () {
  9885. return Engine._DECR;
  9886. },
  9887. enumerable: true,
  9888. configurable: true
  9889. });
  9890. Object.defineProperty(Engine, "INVERT", {
  9891. get: function () {
  9892. return Engine._INVERT;
  9893. },
  9894. enumerable: true,
  9895. configurable: true
  9896. });
  9897. Object.defineProperty(Engine, "INCR_WRAP", {
  9898. get: function () {
  9899. return Engine._INCR_WRAP;
  9900. },
  9901. enumerable: true,
  9902. configurable: true
  9903. });
  9904. Object.defineProperty(Engine, "DECR_WRAP", {
  9905. get: function () {
  9906. return Engine._DECR_WRAP;
  9907. },
  9908. enumerable: true,
  9909. configurable: true
  9910. });
  9911. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  9912. get: function () {
  9913. return Engine._ALPHA_DISABLE;
  9914. },
  9915. enumerable: true,
  9916. configurable: true
  9917. });
  9918. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  9919. get: function () {
  9920. return Engine._ALPHA_ONEONE;
  9921. },
  9922. enumerable: true,
  9923. configurable: true
  9924. });
  9925. Object.defineProperty(Engine, "ALPHA_ADD", {
  9926. get: function () {
  9927. return Engine._ALPHA_ADD;
  9928. },
  9929. enumerable: true,
  9930. configurable: true
  9931. });
  9932. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  9933. get: function () {
  9934. return Engine._ALPHA_COMBINE;
  9935. },
  9936. enumerable: true,
  9937. configurable: true
  9938. });
  9939. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  9940. get: function () {
  9941. return Engine._ALPHA_SUBTRACT;
  9942. },
  9943. enumerable: true,
  9944. configurable: true
  9945. });
  9946. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  9947. get: function () {
  9948. return Engine._ALPHA_MULTIPLY;
  9949. },
  9950. enumerable: true,
  9951. configurable: true
  9952. });
  9953. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  9954. get: function () {
  9955. return Engine._ALPHA_MAXIMIZED;
  9956. },
  9957. enumerable: true,
  9958. configurable: true
  9959. });
  9960. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  9961. get: function () {
  9962. return Engine._ALPHA_PREMULTIPLIED;
  9963. },
  9964. enumerable: true,
  9965. configurable: true
  9966. });
  9967. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  9968. get: function () {
  9969. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  9970. },
  9971. enumerable: true,
  9972. configurable: true
  9973. });
  9974. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  9975. get: function () {
  9976. return Engine._ALPHA_INTERPOLATE;
  9977. },
  9978. enumerable: true,
  9979. configurable: true
  9980. });
  9981. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  9982. get: function () {
  9983. return Engine._ALPHA_SCREENMODE;
  9984. },
  9985. enumerable: true,
  9986. configurable: true
  9987. });
  9988. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  9989. get: function () {
  9990. return Engine._DELAYLOADSTATE_NONE;
  9991. },
  9992. enumerable: true,
  9993. configurable: true
  9994. });
  9995. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  9996. get: function () {
  9997. return Engine._DELAYLOADSTATE_LOADED;
  9998. },
  9999. enumerable: true,
  10000. configurable: true
  10001. });
  10002. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  10003. get: function () {
  10004. return Engine._DELAYLOADSTATE_LOADING;
  10005. },
  10006. enumerable: true,
  10007. configurable: true
  10008. });
  10009. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  10010. get: function () {
  10011. return Engine._DELAYLOADSTATE_NOTLOADED;
  10012. },
  10013. enumerable: true,
  10014. configurable: true
  10015. });
  10016. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  10017. get: function () {
  10018. return Engine._TEXTUREFORMAT_ALPHA;
  10019. },
  10020. enumerable: true,
  10021. configurable: true
  10022. });
  10023. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  10024. get: function () {
  10025. return Engine._TEXTUREFORMAT_LUMINANCE;
  10026. },
  10027. enumerable: true,
  10028. configurable: true
  10029. });
  10030. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  10031. get: function () {
  10032. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  10033. },
  10034. enumerable: true,
  10035. configurable: true
  10036. });
  10037. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  10038. get: function () {
  10039. return Engine._TEXTUREFORMAT_RGB;
  10040. },
  10041. enumerable: true,
  10042. configurable: true
  10043. });
  10044. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  10045. get: function () {
  10046. return Engine._TEXTUREFORMAT_RGBA;
  10047. },
  10048. enumerable: true,
  10049. configurable: true
  10050. });
  10051. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  10052. get: function () {
  10053. return Engine._TEXTURETYPE_UNSIGNED_INT;
  10054. },
  10055. enumerable: true,
  10056. configurable: true
  10057. });
  10058. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  10059. get: function () {
  10060. return Engine._TEXTURETYPE_FLOAT;
  10061. },
  10062. enumerable: true,
  10063. configurable: true
  10064. });
  10065. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  10066. get: function () {
  10067. return Engine._TEXTURETYPE_HALF_FLOAT;
  10068. },
  10069. enumerable: true,
  10070. configurable: true
  10071. });
  10072. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  10073. get: function () {
  10074. return Engine._SCALEMODE_FLOOR;
  10075. },
  10076. enumerable: true,
  10077. configurable: true
  10078. });
  10079. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  10080. get: function () {
  10081. return Engine._SCALEMODE_NEAREST;
  10082. },
  10083. enumerable: true,
  10084. configurable: true
  10085. });
  10086. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  10087. get: function () {
  10088. return Engine._SCALEMODE_CEILING;
  10089. },
  10090. enumerable: true,
  10091. configurable: true
  10092. });
  10093. Object.defineProperty(Engine, "Version", {
  10094. get: function () {
  10095. return "3.2.0-alpha6";
  10096. },
  10097. enumerable: true,
  10098. configurable: true
  10099. });
  10100. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  10101. get: function () {
  10102. return this._vrExclusivePointerMode;
  10103. },
  10104. enumerable: true,
  10105. configurable: true
  10106. });
  10107. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  10108. get: function () {
  10109. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  10110. },
  10111. enumerable: true,
  10112. configurable: true
  10113. });
  10114. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  10115. get: function () {
  10116. return this._webGLVersion < 2 || this.forcePOTTextures;
  10117. },
  10118. enumerable: true,
  10119. configurable: true
  10120. });
  10121. Object.defineProperty(Engine.prototype, "badOS", {
  10122. get: function () {
  10123. return this._badOS;
  10124. },
  10125. enumerable: true,
  10126. configurable: true
  10127. });
  10128. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  10129. get: function () {
  10130. return this._badDesktopOS;
  10131. },
  10132. enumerable: true,
  10133. configurable: true
  10134. });
  10135. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  10136. get: function () {
  10137. return this._performanceMonitor;
  10138. },
  10139. enumerable: true,
  10140. configurable: true
  10141. });
  10142. Object.defineProperty(Engine.prototype, "texturesSupported", {
  10143. get: function () {
  10144. return this._texturesSupported;
  10145. },
  10146. enumerable: true,
  10147. configurable: true
  10148. });
  10149. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  10150. get: function () {
  10151. return this._textureFormatInUse;
  10152. },
  10153. enumerable: true,
  10154. configurable: true
  10155. });
  10156. Object.defineProperty(Engine.prototype, "currentViewport", {
  10157. get: function () {
  10158. return this._cachedViewport;
  10159. },
  10160. enumerable: true,
  10161. configurable: true
  10162. });
  10163. Object.defineProperty(Engine.prototype, "emptyTexture", {
  10164. // Empty texture
  10165. get: function () {
  10166. if (!this._emptyTexture) {
  10167. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10168. }
  10169. return this._emptyTexture;
  10170. },
  10171. enumerable: true,
  10172. configurable: true
  10173. });
  10174. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  10175. get: function () {
  10176. if (!this._emptyTexture3D) {
  10177. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10178. }
  10179. return this._emptyTexture3D;
  10180. },
  10181. enumerable: true,
  10182. configurable: true
  10183. });
  10184. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  10185. get: function () {
  10186. if (!this._emptyCubeTexture) {
  10187. var faceData = new Uint8Array(4);
  10188. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  10189. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10190. }
  10191. return this._emptyCubeTexture;
  10192. },
  10193. enumerable: true,
  10194. configurable: true
  10195. });
  10196. Engine.prototype._rebuildInternalTextures = function () {
  10197. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  10198. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  10199. var internalTexture = currentState_1[_i];
  10200. internalTexture._rebuild();
  10201. }
  10202. };
  10203. Engine.prototype._rebuildEffects = function () {
  10204. for (var key in this._compiledEffects) {
  10205. var effect = this._compiledEffects[key];
  10206. effect._prepareEffect();
  10207. }
  10208. BABYLON.Effect.ResetCache();
  10209. };
  10210. Engine.prototype._rebuildBuffers = function () {
  10211. // Index / Vertex
  10212. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  10213. var scene = _a[_i];
  10214. scene.resetCachedMaterial();
  10215. scene._rebuildGeometries();
  10216. scene._rebuildTextures();
  10217. }
  10218. // Uniforms
  10219. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  10220. var uniformBuffer = _c[_b];
  10221. uniformBuffer._rebuild();
  10222. }
  10223. };
  10224. Engine.prototype._initGLContext = function () {
  10225. // Caps
  10226. this._caps = new EngineCapabilities();
  10227. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  10228. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  10229. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  10230. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  10231. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  10232. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  10233. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  10234. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  10235. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  10236. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  10237. // Infos
  10238. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  10239. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  10240. if (rendererInfo != null) {
  10241. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  10242. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  10243. }
  10244. if (!this._glVendor) {
  10245. this._glVendor = "Unknown vendor";
  10246. }
  10247. if (!this._glRenderer) {
  10248. this._glRenderer = "Unknown renderer";
  10249. }
  10250. // Constants
  10251. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  10252. if (this._gl.RGBA16F !== 0x881A) {
  10253. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  10254. }
  10255. if (this._gl.RGBA32F !== 0x8814) {
  10256. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  10257. }
  10258. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  10259. this._gl.DEPTH24_STENCIL8 = 35056;
  10260. }
  10261. // Extensions
  10262. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  10263. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  10264. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  10265. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  10266. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  10267. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  10268. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  10269. 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');
  10270. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  10271. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  10272. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  10273. this._caps.highPrecisionShaderSupported = true;
  10274. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  10275. if (this._caps.timerQuery) {
  10276. if (this._webGLVersion === 1) {
  10277. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  10278. }
  10279. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  10280. }
  10281. // Checks if some of the format renders first to allow the use of webgl inspector.
  10282. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  10283. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  10284. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  10285. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  10286. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  10287. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  10288. if (this._webGLVersion > 1) {
  10289. this._gl.HALF_FLOAT_OES = 0x140B;
  10290. }
  10291. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  10292. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  10293. // Draw buffers
  10294. if (this._webGLVersion > 1) {
  10295. this._caps.drawBuffersExtension = true;
  10296. }
  10297. else {
  10298. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  10299. if (drawBuffersExtension !== null) {
  10300. this._caps.drawBuffersExtension = true;
  10301. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  10302. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  10303. for (var i = 0; i < 16; i++) {
  10304. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  10305. }
  10306. }
  10307. else {
  10308. this._caps.drawBuffersExtension = false;
  10309. }
  10310. }
  10311. // Depth Texture
  10312. if (this._webGLVersion > 1) {
  10313. this._caps.depthTextureExtension = true;
  10314. }
  10315. else {
  10316. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  10317. if (depthTextureExtension != null) {
  10318. this._caps.depthTextureExtension = true;
  10319. }
  10320. }
  10321. // Vertex array object
  10322. if (this._webGLVersion > 1) {
  10323. this._caps.vertexArrayObject = true;
  10324. }
  10325. else {
  10326. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  10327. if (vertexArrayObjectExtension != null) {
  10328. this._caps.vertexArrayObject = true;
  10329. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  10330. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  10331. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  10332. }
  10333. else {
  10334. this._caps.vertexArrayObject = false;
  10335. }
  10336. }
  10337. // Instances count
  10338. if (this._webGLVersion > 1) {
  10339. this._caps.instancedArrays = true;
  10340. }
  10341. else {
  10342. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  10343. if (instanceExtension != null) {
  10344. this._caps.instancedArrays = true;
  10345. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  10346. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  10347. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  10348. }
  10349. else {
  10350. this._caps.instancedArrays = false;
  10351. }
  10352. }
  10353. // Intelligently add supported compressed formats in order to check for.
  10354. // Check for ASTC support first as it is most powerful and to be very cross platform.
  10355. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  10356. // Likely no hardware which supports both PVR & DXT, so order matters little.
  10357. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  10358. if (this._caps.astc)
  10359. this.texturesSupported.push('-astc.ktx');
  10360. if (this._caps.s3tc)
  10361. this.texturesSupported.push('-dxt.ktx');
  10362. if (this._caps.pvrtc)
  10363. this.texturesSupported.push('-pvrtc.ktx');
  10364. if (this._caps.etc2)
  10365. this.texturesSupported.push('-etc2.ktx');
  10366. if (this._caps.etc1)
  10367. this.texturesSupported.push('-etc1.ktx');
  10368. if (this._gl.getShaderPrecisionFormat) {
  10369. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  10370. if (highp) {
  10371. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  10372. }
  10373. }
  10374. // Depth buffer
  10375. this.setDepthBuffer(true);
  10376. this.setDepthFunctionToLessOrEqual();
  10377. this.setDepthWrite(true);
  10378. // Texture maps
  10379. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  10380. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  10381. this._nextFreeTextureSlots.push(slot);
  10382. }
  10383. };
  10384. Object.defineProperty(Engine.prototype, "webGLVersion", {
  10385. get: function () {
  10386. return this._webGLVersion;
  10387. },
  10388. enumerable: true,
  10389. configurable: true
  10390. });
  10391. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  10392. /**
  10393. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  10394. */
  10395. get: function () {
  10396. return this._isStencilEnable;
  10397. },
  10398. enumerable: true,
  10399. configurable: true
  10400. });
  10401. Engine.prototype._prepareWorkingCanvas = function () {
  10402. if (this._workingCanvas) {
  10403. return;
  10404. }
  10405. this._workingCanvas = document.createElement("canvas");
  10406. var context = this._workingCanvas.getContext("2d");
  10407. if (context) {
  10408. this._workingContext = context;
  10409. }
  10410. };
  10411. Engine.prototype.resetTextureCache = function () {
  10412. for (var key in this._boundTexturesCache) {
  10413. var boundTexture = this._boundTexturesCache[key];
  10414. if (boundTexture) {
  10415. this._removeDesignatedSlot(boundTexture);
  10416. }
  10417. this._boundTexturesCache[key] = null;
  10418. }
  10419. this._nextFreeTextureSlots = [];
  10420. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  10421. this._nextFreeTextureSlots.push(slot);
  10422. }
  10423. this._currentTextureChannel = -1;
  10424. };
  10425. Engine.prototype.isDeterministicLockStep = function () {
  10426. return this._deterministicLockstep;
  10427. };
  10428. Engine.prototype.getLockstepMaxSteps = function () {
  10429. return this._lockstepMaxSteps;
  10430. };
  10431. Engine.prototype.getGlInfo = function () {
  10432. return {
  10433. vendor: this._glVendor,
  10434. renderer: this._glRenderer,
  10435. version: this._glVersion
  10436. };
  10437. };
  10438. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  10439. if (useScreen === void 0) { useScreen = false; }
  10440. var viewport = camera.viewport;
  10441. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  10442. };
  10443. Engine.prototype.getRenderWidth = function (useScreen) {
  10444. if (useScreen === void 0) { useScreen = false; }
  10445. if (!useScreen && this._currentRenderTarget) {
  10446. return this._currentRenderTarget.width;
  10447. }
  10448. return this._gl.drawingBufferWidth;
  10449. };
  10450. Engine.prototype.getRenderHeight = function (useScreen) {
  10451. if (useScreen === void 0) { useScreen = false; }
  10452. if (!useScreen && this._currentRenderTarget) {
  10453. return this._currentRenderTarget.height;
  10454. }
  10455. return this._gl.drawingBufferHeight;
  10456. };
  10457. Engine.prototype.getRenderingCanvas = function () {
  10458. return this._renderingCanvas;
  10459. };
  10460. Engine.prototype.getRenderingCanvasClientRect = function () {
  10461. if (!this._renderingCanvas) {
  10462. return null;
  10463. }
  10464. return this._renderingCanvas.getBoundingClientRect();
  10465. };
  10466. Engine.prototype.setHardwareScalingLevel = function (level) {
  10467. this._hardwareScalingLevel = level;
  10468. this.resize();
  10469. };
  10470. Engine.prototype.getHardwareScalingLevel = function () {
  10471. return this._hardwareScalingLevel;
  10472. };
  10473. Engine.prototype.getLoadedTexturesCache = function () {
  10474. return this._internalTexturesCache;
  10475. };
  10476. Engine.prototype.getCaps = function () {
  10477. return this._caps;
  10478. };
  10479. Object.defineProperty(Engine.prototype, "drawCalls", {
  10480. /** The number of draw calls submitted last frame */
  10481. get: function () {
  10482. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  10483. return 0;
  10484. },
  10485. enumerable: true,
  10486. configurable: true
  10487. });
  10488. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  10489. get: function () {
  10490. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  10491. return null;
  10492. },
  10493. enumerable: true,
  10494. configurable: true
  10495. });
  10496. Engine.prototype.getDepthFunction = function () {
  10497. return this._depthCullingState.depthFunc;
  10498. };
  10499. Engine.prototype.setDepthFunction = function (depthFunc) {
  10500. this._depthCullingState.depthFunc = depthFunc;
  10501. };
  10502. Engine.prototype.setDepthFunctionToGreater = function () {
  10503. this._depthCullingState.depthFunc = this._gl.GREATER;
  10504. };
  10505. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  10506. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  10507. };
  10508. Engine.prototype.setDepthFunctionToLess = function () {
  10509. this._depthCullingState.depthFunc = this._gl.LESS;
  10510. };
  10511. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  10512. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  10513. };
  10514. Engine.prototype.getStencilBuffer = function () {
  10515. return this._stencilState.stencilTest;
  10516. };
  10517. Engine.prototype.setStencilBuffer = function (enable) {
  10518. this._stencilState.stencilTest = enable;
  10519. };
  10520. Engine.prototype.getStencilMask = function () {
  10521. return this._stencilState.stencilMask;
  10522. };
  10523. Engine.prototype.setStencilMask = function (mask) {
  10524. this._stencilState.stencilMask = mask;
  10525. };
  10526. Engine.prototype.getStencilFunction = function () {
  10527. return this._stencilState.stencilFunc;
  10528. };
  10529. Engine.prototype.getStencilFunctionReference = function () {
  10530. return this._stencilState.stencilFuncRef;
  10531. };
  10532. Engine.prototype.getStencilFunctionMask = function () {
  10533. return this._stencilState.stencilFuncMask;
  10534. };
  10535. Engine.prototype.setStencilFunction = function (stencilFunc) {
  10536. this._stencilState.stencilFunc = stencilFunc;
  10537. };
  10538. Engine.prototype.setStencilFunctionReference = function (reference) {
  10539. this._stencilState.stencilFuncRef = reference;
  10540. };
  10541. Engine.prototype.setStencilFunctionMask = function (mask) {
  10542. this._stencilState.stencilFuncMask = mask;
  10543. };
  10544. Engine.prototype.getStencilOperationFail = function () {
  10545. return this._stencilState.stencilOpStencilFail;
  10546. };
  10547. Engine.prototype.getStencilOperationDepthFail = function () {
  10548. return this._stencilState.stencilOpDepthFail;
  10549. };
  10550. Engine.prototype.getStencilOperationPass = function () {
  10551. return this._stencilState.stencilOpStencilDepthPass;
  10552. };
  10553. Engine.prototype.setStencilOperationFail = function (operation) {
  10554. this._stencilState.stencilOpStencilFail = operation;
  10555. };
  10556. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  10557. this._stencilState.stencilOpDepthFail = operation;
  10558. };
  10559. Engine.prototype.setStencilOperationPass = function (operation) {
  10560. this._stencilState.stencilOpStencilDepthPass = operation;
  10561. };
  10562. Engine.prototype.setDitheringState = function (value) {
  10563. if (value) {
  10564. this._gl.enable(this._gl.DITHER);
  10565. }
  10566. else {
  10567. this._gl.disable(this._gl.DITHER);
  10568. }
  10569. };
  10570. Engine.prototype.setRasterizerState = function (value) {
  10571. if (value) {
  10572. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  10573. }
  10574. else {
  10575. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  10576. }
  10577. };
  10578. /**
  10579. * stop executing a render loop function and remove it from the execution array
  10580. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  10581. */
  10582. Engine.prototype.stopRenderLoop = function (renderFunction) {
  10583. if (!renderFunction) {
  10584. this._activeRenderLoops = [];
  10585. return;
  10586. }
  10587. var index = this._activeRenderLoops.indexOf(renderFunction);
  10588. if (index >= 0) {
  10589. this._activeRenderLoops.splice(index, 1);
  10590. }
  10591. };
  10592. Engine.prototype._renderLoop = function () {
  10593. if (!this._contextWasLost) {
  10594. var shouldRender = true;
  10595. if (!this.renderEvenInBackground && this._windowIsBackground) {
  10596. shouldRender = false;
  10597. }
  10598. if (shouldRender) {
  10599. // Start new frame
  10600. this.beginFrame();
  10601. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  10602. var renderFunction = this._activeRenderLoops[index];
  10603. renderFunction();
  10604. }
  10605. // Present
  10606. this.endFrame();
  10607. }
  10608. }
  10609. if (this._activeRenderLoops.length > 0) {
  10610. // Register new frame
  10611. var requester = null;
  10612. if (this._vrDisplay && this._vrDisplay.isPresenting)
  10613. requester = this._vrDisplay;
  10614. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  10615. }
  10616. else {
  10617. this._renderingQueueLaunched = false;
  10618. }
  10619. };
  10620. /**
  10621. * Register and execute a render loop. The engine can have more than one render function.
  10622. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  10623. * @example
  10624. * engine.runRenderLoop(function () {
  10625. * scene.render()
  10626. * })
  10627. */
  10628. Engine.prototype.runRenderLoop = function (renderFunction) {
  10629. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  10630. return;
  10631. }
  10632. this._activeRenderLoops.push(renderFunction);
  10633. if (!this._renderingQueueLaunched) {
  10634. this._renderingQueueLaunched = true;
  10635. this._bindedRenderFunction = this._renderLoop.bind(this);
  10636. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  10637. }
  10638. };
  10639. /**
  10640. * Toggle full screen mode.
  10641. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  10642. * @param {any} options - an options object to be sent to the requestFullscreen function
  10643. */
  10644. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  10645. if (this.isFullscreen) {
  10646. BABYLON.Tools.ExitFullscreen();
  10647. }
  10648. else {
  10649. this._pointerLockRequested = requestPointerLock;
  10650. if (this._renderingCanvas) {
  10651. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  10652. }
  10653. }
  10654. };
  10655. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  10656. if (stencil === void 0) { stencil = false; }
  10657. this.applyStates();
  10658. var mode = 0;
  10659. if (backBuffer && color) {
  10660. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  10661. mode |= this._gl.COLOR_BUFFER_BIT;
  10662. }
  10663. if (depth) {
  10664. this._gl.clearDepth(1.0);
  10665. mode |= this._gl.DEPTH_BUFFER_BIT;
  10666. }
  10667. if (stencil) {
  10668. this._gl.clearStencil(0);
  10669. mode |= this._gl.STENCIL_BUFFER_BIT;
  10670. }
  10671. this._gl.clear(mode);
  10672. };
  10673. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  10674. var gl = this._gl;
  10675. // Save state
  10676. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  10677. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  10678. // Change state
  10679. gl.enable(gl.SCISSOR_TEST);
  10680. gl.scissor(x, y, width, height);
  10681. // Clear
  10682. this.clear(clearColor, true, true, true);
  10683. // Restore state
  10684. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  10685. if (curScissor === true) {
  10686. gl.enable(gl.SCISSOR_TEST);
  10687. }
  10688. else {
  10689. gl.disable(gl.SCISSOR_TEST);
  10690. }
  10691. };
  10692. /**
  10693. * Set the WebGL's viewport
  10694. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  10695. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  10696. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  10697. */
  10698. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  10699. var width = requiredWidth || this.getRenderWidth();
  10700. var height = requiredHeight || this.getRenderHeight();
  10701. var x = viewport.x || 0;
  10702. var y = viewport.y || 0;
  10703. this._cachedViewport = viewport;
  10704. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  10705. };
  10706. /**
  10707. * Directly set the WebGL Viewport
  10708. * The x, y, width & height are directly passed to the WebGL call
  10709. * @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.
  10710. */
  10711. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  10712. var currentViewport = this._cachedViewport;
  10713. this._cachedViewport = null;
  10714. this._gl.viewport(x, y, width, height);
  10715. return currentViewport;
  10716. };
  10717. Engine.prototype.beginFrame = function () {
  10718. this.onBeginFrameObservable.notifyObservers(this);
  10719. this._measureFps();
  10720. };
  10721. Engine.prototype.endFrame = function () {
  10722. //force a flush in case we are using a bad OS.
  10723. if (this._badOS) {
  10724. this.flushFramebuffer();
  10725. }
  10726. //submit frame to the vr device, if enabled
  10727. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  10728. // TODO: We should only submit the frame if we read frameData successfully.
  10729. this._vrDisplay.submitFrame();
  10730. }
  10731. this.onEndFrameObservable.notifyObservers(this);
  10732. };
  10733. /**
  10734. * resize the view according to the canvas' size.
  10735. * @example
  10736. * window.addEventListener("resize", function () {
  10737. * engine.resize();
  10738. * });
  10739. */
  10740. Engine.prototype.resize = function () {
  10741. // We're not resizing the size of the canvas while in VR mode & presenting
  10742. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  10743. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  10744. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  10745. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  10746. }
  10747. };
  10748. /**
  10749. * force a specific size of the canvas
  10750. * @param {number} width - the new canvas' width
  10751. * @param {number} height - the new canvas' height
  10752. */
  10753. Engine.prototype.setSize = function (width, height) {
  10754. if (!this._renderingCanvas) {
  10755. return;
  10756. }
  10757. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  10758. return;
  10759. }
  10760. this._renderingCanvas.width = width;
  10761. this._renderingCanvas.height = height;
  10762. for (var index = 0; index < this.scenes.length; index++) {
  10763. var scene = this.scenes[index];
  10764. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  10765. var cam = scene.cameras[camIndex];
  10766. cam._currentRenderId = 0;
  10767. }
  10768. }
  10769. if (this.onResizeObservable.hasObservers) {
  10770. this.onResizeObservable.notifyObservers(this);
  10771. }
  10772. };
  10773. // WebVR functions
  10774. Engine.prototype.isVRDevicePresent = function () {
  10775. return !!this._vrDisplay;
  10776. };
  10777. Engine.prototype.getVRDevice = function () {
  10778. return this._vrDisplay;
  10779. };
  10780. Engine.prototype.initWebVR = function () {
  10781. var _this = this;
  10782. var notifyObservers = function () {
  10783. var eventArgs = {
  10784. vrDisplay: _this._vrDisplay,
  10785. vrSupported: _this._vrSupported
  10786. };
  10787. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  10788. };
  10789. if (!this._onVrDisplayConnect) {
  10790. this._onVrDisplayConnect = function (event) {
  10791. _this._vrDisplay = event.display;
  10792. notifyObservers();
  10793. };
  10794. this._onVrDisplayDisconnect = function () {
  10795. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  10796. _this._vrDisplay = undefined;
  10797. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  10798. notifyObservers();
  10799. };
  10800. this._onVrDisplayPresentChange = function () {
  10801. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  10802. };
  10803. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  10804. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  10805. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  10806. }
  10807. this._getVRDisplays(notifyObservers);
  10808. return this.onVRDisplayChangedObservable;
  10809. };
  10810. Engine.prototype.enableVR = function () {
  10811. var _this = this;
  10812. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  10813. var onResolved = function () {
  10814. _this.onVRRequestPresentComplete.notifyObservers(true);
  10815. _this._onVRFullScreenTriggered();
  10816. };
  10817. var onRejected = function () {
  10818. _this.onVRRequestPresentComplete.notifyObservers(false);
  10819. };
  10820. this.onVRRequestPresentStart.notifyObservers(this);
  10821. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  10822. }
  10823. };
  10824. Engine.prototype.disableVR = function () {
  10825. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  10826. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  10827. }
  10828. };
  10829. Engine.prototype._getVRDisplays = function (callback) {
  10830. var _this = this;
  10831. var getWebVRDevices = function (devices) {
  10832. _this._vrSupported = true;
  10833. // note that devices may actually be an empty array. This is fine;
  10834. // we expect this._vrDisplay to be undefined in this case.
  10835. return _this._vrDisplay = devices[0];
  10836. };
  10837. if (navigator.getVRDisplays) {
  10838. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  10839. // TODO: System CANNOT support WebVR, despite API presence.
  10840. _this._vrSupported = false;
  10841. callback();
  10842. });
  10843. }
  10844. else {
  10845. // TODO: Browser does not support WebVR
  10846. this._vrDisplay = undefined;
  10847. this._vrSupported = false;
  10848. callback();
  10849. }
  10850. };
  10851. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  10852. if (this._currentRenderTarget) {
  10853. this.unBindFramebuffer(this._currentRenderTarget);
  10854. }
  10855. this._currentRenderTarget = texture;
  10856. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  10857. var gl = this._gl;
  10858. if (texture.isCube) {
  10859. if (faceIndex === undefined) {
  10860. faceIndex = 0;
  10861. }
  10862. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  10863. }
  10864. if (this._cachedViewport && !forceFullscreenViewport) {
  10865. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  10866. }
  10867. else {
  10868. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  10869. }
  10870. this.wipeCaches();
  10871. };
  10872. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  10873. if (this._currentFramebuffer !== framebuffer) {
  10874. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  10875. this._currentFramebuffer = framebuffer;
  10876. }
  10877. };
  10878. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  10879. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  10880. this._currentRenderTarget = null;
  10881. // If MSAA, we need to bitblt back to main texture
  10882. var gl = this._gl;
  10883. if (texture._MSAAFramebuffer) {
  10884. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  10885. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  10886. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  10887. }
  10888. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  10889. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  10890. gl.generateMipmap(gl.TEXTURE_2D);
  10891. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10892. }
  10893. if (onBeforeUnbind) {
  10894. if (texture._MSAAFramebuffer) {
  10895. // Bind the correct framebuffer
  10896. this.bindUnboundFramebuffer(texture._framebuffer);
  10897. }
  10898. onBeforeUnbind();
  10899. }
  10900. this.bindUnboundFramebuffer(null);
  10901. };
  10902. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  10903. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  10904. this._currentRenderTarget = null;
  10905. // If MSAA, we need to bitblt back to main texture
  10906. var gl = this._gl;
  10907. if (textures[0]._MSAAFramebuffer) {
  10908. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  10909. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  10910. var attachments = textures[0]._attachments;
  10911. if (!attachments) {
  10912. attachments = new Array(textures.length);
  10913. textures[0]._attachments = attachments;
  10914. }
  10915. for (var i = 0; i < textures.length; i++) {
  10916. var texture = textures[i];
  10917. for (var j = 0; j < attachments.length; j++) {
  10918. attachments[j] = gl.NONE;
  10919. }
  10920. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10921. gl.readBuffer(attachments[i]);
  10922. gl.drawBuffers(attachments);
  10923. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  10924. }
  10925. for (var i = 0; i < attachments.length; i++) {
  10926. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10927. }
  10928. gl.drawBuffers(attachments);
  10929. }
  10930. for (var i = 0; i < textures.length; i++) {
  10931. var texture = textures[i];
  10932. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  10933. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10934. gl.generateMipmap(gl.TEXTURE_2D);
  10935. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10936. }
  10937. }
  10938. if (onBeforeUnbind) {
  10939. if (textures[0]._MSAAFramebuffer) {
  10940. // Bind the correct framebuffer
  10941. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  10942. }
  10943. onBeforeUnbind();
  10944. }
  10945. this.bindUnboundFramebuffer(null);
  10946. };
  10947. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  10948. if (texture.generateMipMaps) {
  10949. var gl = this._gl;
  10950. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  10951. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10952. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10953. }
  10954. };
  10955. Engine.prototype.flushFramebuffer = function () {
  10956. this._gl.flush();
  10957. };
  10958. Engine.prototype.restoreDefaultFramebuffer = function () {
  10959. if (this._currentRenderTarget) {
  10960. this.unBindFramebuffer(this._currentRenderTarget);
  10961. }
  10962. else {
  10963. this.bindUnboundFramebuffer(null);
  10964. }
  10965. if (this._cachedViewport) {
  10966. this.setViewport(this._cachedViewport);
  10967. }
  10968. this.wipeCaches();
  10969. };
  10970. // UBOs
  10971. Engine.prototype.createUniformBuffer = function (elements) {
  10972. var ubo = this._gl.createBuffer();
  10973. if (!ubo) {
  10974. throw new Error("Unable to create uniform buffer");
  10975. }
  10976. this.bindUniformBuffer(ubo);
  10977. if (elements instanceof Float32Array) {
  10978. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  10979. }
  10980. else {
  10981. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  10982. }
  10983. this.bindUniformBuffer(null);
  10984. ubo.references = 1;
  10985. return ubo;
  10986. };
  10987. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  10988. var ubo = this._gl.createBuffer();
  10989. if (!ubo) {
  10990. throw new Error("Unable to create dynamic uniform buffer");
  10991. }
  10992. this.bindUniformBuffer(ubo);
  10993. if (elements instanceof Float32Array) {
  10994. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  10995. }
  10996. else {
  10997. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  10998. }
  10999. this.bindUniformBuffer(null);
  11000. ubo.references = 1;
  11001. return ubo;
  11002. };
  11003. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  11004. this.bindUniformBuffer(uniformBuffer);
  11005. if (offset === undefined) {
  11006. offset = 0;
  11007. }
  11008. if (count === undefined) {
  11009. if (elements instanceof Float32Array) {
  11010. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  11011. }
  11012. else {
  11013. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  11014. }
  11015. }
  11016. else {
  11017. if (elements instanceof Float32Array) {
  11018. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  11019. }
  11020. else {
  11021. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  11022. }
  11023. }
  11024. this.bindUniformBuffer(null);
  11025. };
  11026. // VBOs
  11027. Engine.prototype._resetVertexBufferBinding = function () {
  11028. this.bindArrayBuffer(null);
  11029. this._cachedVertexBuffers = null;
  11030. };
  11031. Engine.prototype.createVertexBuffer = function (vertices) {
  11032. var vbo = this._gl.createBuffer();
  11033. if (!vbo) {
  11034. throw new Error("Unable to create vertex buffer");
  11035. }
  11036. this.bindArrayBuffer(vbo);
  11037. if (vertices instanceof Float32Array) {
  11038. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  11039. }
  11040. else {
  11041. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  11042. }
  11043. this._resetVertexBufferBinding();
  11044. vbo.references = 1;
  11045. return vbo;
  11046. };
  11047. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  11048. var vbo = this._gl.createBuffer();
  11049. if (!vbo) {
  11050. throw new Error("Unable to create dynamic vertex buffer");
  11051. }
  11052. this.bindArrayBuffer(vbo);
  11053. if (vertices instanceof Float32Array) {
  11054. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  11055. }
  11056. else {
  11057. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  11058. }
  11059. this._resetVertexBufferBinding();
  11060. vbo.references = 1;
  11061. return vbo;
  11062. };
  11063. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  11064. if (offset === void 0) { offset = 0; }
  11065. // Force cache update
  11066. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  11067. this.bindIndexBuffer(indexBuffer);
  11068. var arrayBuffer;
  11069. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  11070. arrayBuffer = indices;
  11071. }
  11072. else {
  11073. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  11074. }
  11075. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  11076. this._resetIndexBufferBinding();
  11077. };
  11078. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  11079. this.bindArrayBuffer(vertexBuffer);
  11080. if (offset === undefined) {
  11081. offset = 0;
  11082. }
  11083. if (count === undefined) {
  11084. if (vertices instanceof Float32Array) {
  11085. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  11086. }
  11087. else {
  11088. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  11089. }
  11090. }
  11091. else {
  11092. if (vertices instanceof Float32Array) {
  11093. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  11094. }
  11095. else {
  11096. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  11097. }
  11098. }
  11099. this._resetVertexBufferBinding();
  11100. };
  11101. Engine.prototype._resetIndexBufferBinding = function () {
  11102. this.bindIndexBuffer(null);
  11103. this._cachedIndexBuffer = null;
  11104. };
  11105. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  11106. var vbo = this._gl.createBuffer();
  11107. if (!vbo) {
  11108. throw new Error("Unable to create index buffer");
  11109. }
  11110. this.bindIndexBuffer(vbo);
  11111. // Check for 32 bits indices
  11112. var arrayBuffer;
  11113. var need32Bits = false;
  11114. if (indices instanceof Uint16Array) {
  11115. arrayBuffer = indices;
  11116. }
  11117. else {
  11118. //check 32 bit support
  11119. if (this._caps.uintIndices) {
  11120. if (indices instanceof Uint32Array) {
  11121. arrayBuffer = indices;
  11122. need32Bits = true;
  11123. }
  11124. else {
  11125. //number[] or Int32Array, check if 32 bit is necessary
  11126. for (var index = 0; index < indices.length; index++) {
  11127. if (indices[index] > 65535) {
  11128. need32Bits = true;
  11129. break;
  11130. }
  11131. }
  11132. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  11133. }
  11134. }
  11135. else {
  11136. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  11137. arrayBuffer = new Uint16Array(indices);
  11138. }
  11139. }
  11140. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  11141. this._resetIndexBufferBinding();
  11142. vbo.references = 1;
  11143. vbo.is32Bits = need32Bits;
  11144. return vbo;
  11145. };
  11146. Engine.prototype.bindArrayBuffer = function (buffer) {
  11147. if (!this._vaoRecordInProgress) {
  11148. this._unbindVertexArrayObject();
  11149. }
  11150. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  11151. };
  11152. Engine.prototype.bindUniformBuffer = function (buffer) {
  11153. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  11154. };
  11155. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  11156. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  11157. };
  11158. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  11159. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  11160. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  11161. };
  11162. ;
  11163. Engine.prototype.bindIndexBuffer = function (buffer) {
  11164. if (!this._vaoRecordInProgress) {
  11165. this._unbindVertexArrayObject();
  11166. }
  11167. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  11168. };
  11169. Engine.prototype.bindBuffer = function (buffer, target) {
  11170. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  11171. this._gl.bindBuffer(target, buffer);
  11172. this._currentBoundBuffer[target] = buffer;
  11173. }
  11174. };
  11175. Engine.prototype.updateArrayBuffer = function (data) {
  11176. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  11177. };
  11178. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  11179. var pointer = this._currentBufferPointers[indx];
  11180. var changed = false;
  11181. if (!pointer.active) {
  11182. changed = true;
  11183. pointer.active = true;
  11184. pointer.index = indx;
  11185. pointer.size = size;
  11186. pointer.type = type;
  11187. pointer.normalized = normalized;
  11188. pointer.stride = stride;
  11189. pointer.offset = offset;
  11190. pointer.buffer = buffer;
  11191. }
  11192. else {
  11193. if (pointer.buffer !== buffer) {
  11194. pointer.buffer = buffer;
  11195. changed = true;
  11196. }
  11197. if (pointer.size !== size) {
  11198. pointer.size = size;
  11199. changed = true;
  11200. }
  11201. if (pointer.type !== type) {
  11202. pointer.type = type;
  11203. changed = true;
  11204. }
  11205. if (pointer.normalized !== normalized) {
  11206. pointer.normalized = normalized;
  11207. changed = true;
  11208. }
  11209. if (pointer.stride !== stride) {
  11210. pointer.stride = stride;
  11211. changed = true;
  11212. }
  11213. if (pointer.offset !== offset) {
  11214. pointer.offset = offset;
  11215. changed = true;
  11216. }
  11217. }
  11218. if (changed || this._vaoRecordInProgress) {
  11219. this.bindArrayBuffer(buffer);
  11220. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  11221. }
  11222. };
  11223. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  11224. if (indexBuffer == null) {
  11225. return;
  11226. }
  11227. if (this._cachedIndexBuffer !== indexBuffer) {
  11228. this._cachedIndexBuffer = indexBuffer;
  11229. this.bindIndexBuffer(indexBuffer);
  11230. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  11231. }
  11232. };
  11233. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  11234. var attributes = effect.getAttributesNames();
  11235. if (!this._vaoRecordInProgress) {
  11236. this._unbindVertexArrayObject();
  11237. }
  11238. this.unbindAllAttributes();
  11239. for (var index = 0; index < attributes.length; index++) {
  11240. var order = effect.getAttributeLocation(index);
  11241. if (order >= 0) {
  11242. var vertexBuffer = vertexBuffers[attributes[index]];
  11243. if (!vertexBuffer) {
  11244. continue;
  11245. }
  11246. this._gl.enableVertexAttribArray(order);
  11247. if (!this._vaoRecordInProgress) {
  11248. this._vertexAttribArraysEnabled[order] = true;
  11249. }
  11250. var buffer = vertexBuffer.getBuffer();
  11251. if (buffer) {
  11252. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  11253. if (vertexBuffer.getIsInstanced()) {
  11254. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  11255. if (!this._vaoRecordInProgress) {
  11256. this._currentInstanceLocations.push(order);
  11257. this._currentInstanceBuffers.push(buffer);
  11258. }
  11259. }
  11260. }
  11261. }
  11262. }
  11263. };
  11264. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  11265. var vao = this._gl.createVertexArray();
  11266. this._vaoRecordInProgress = true;
  11267. this._gl.bindVertexArray(vao);
  11268. this._mustWipeVertexAttributes = true;
  11269. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  11270. this.bindIndexBuffer(indexBuffer);
  11271. this._vaoRecordInProgress = false;
  11272. this._gl.bindVertexArray(null);
  11273. return vao;
  11274. };
  11275. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  11276. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  11277. this._cachedVertexArrayObject = vertexArrayObject;
  11278. this._gl.bindVertexArray(vertexArrayObject);
  11279. this._cachedVertexBuffers = null;
  11280. this._cachedIndexBuffer = null;
  11281. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  11282. this._mustWipeVertexAttributes = true;
  11283. }
  11284. };
  11285. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  11286. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  11287. this._cachedVertexBuffers = vertexBuffer;
  11288. this._cachedEffectForVertexBuffers = effect;
  11289. var attributesCount = effect.getAttributesCount();
  11290. this._unbindVertexArrayObject();
  11291. this.unbindAllAttributes();
  11292. var offset = 0;
  11293. for (var index = 0; index < attributesCount; index++) {
  11294. if (index < vertexDeclaration.length) {
  11295. var order = effect.getAttributeLocation(index);
  11296. if (order >= 0) {
  11297. this._gl.enableVertexAttribArray(order);
  11298. this._vertexAttribArraysEnabled[order] = true;
  11299. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  11300. }
  11301. offset += vertexDeclaration[index] * 4;
  11302. }
  11303. }
  11304. }
  11305. this._bindIndexBufferWithCache(indexBuffer);
  11306. };
  11307. Engine.prototype._unbindVertexArrayObject = function () {
  11308. if (!this._cachedVertexArrayObject) {
  11309. return;
  11310. }
  11311. this._cachedVertexArrayObject = null;
  11312. this._gl.bindVertexArray(null);
  11313. };
  11314. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  11315. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  11316. this._cachedVertexBuffers = vertexBuffers;
  11317. this._cachedEffectForVertexBuffers = effect;
  11318. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  11319. }
  11320. this._bindIndexBufferWithCache(indexBuffer);
  11321. };
  11322. Engine.prototype.unbindInstanceAttributes = function () {
  11323. var boundBuffer;
  11324. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  11325. var instancesBuffer = this._currentInstanceBuffers[i];
  11326. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  11327. boundBuffer = instancesBuffer;
  11328. this.bindArrayBuffer(instancesBuffer);
  11329. }
  11330. var offsetLocation = this._currentInstanceLocations[i];
  11331. this._gl.vertexAttribDivisor(offsetLocation, 0);
  11332. }
  11333. this._currentInstanceBuffers.length = 0;
  11334. this._currentInstanceLocations.length = 0;
  11335. };
  11336. Engine.prototype.releaseVertexArrayObject = function (vao) {
  11337. this._gl.deleteVertexArray(vao);
  11338. };
  11339. Engine.prototype._releaseBuffer = function (buffer) {
  11340. buffer.references--;
  11341. if (buffer.references === 0) {
  11342. this._gl.deleteBuffer(buffer);
  11343. return true;
  11344. }
  11345. return false;
  11346. };
  11347. Engine.prototype.createInstancesBuffer = function (capacity) {
  11348. var buffer = this._gl.createBuffer();
  11349. if (!buffer) {
  11350. throw new Error("Unable to create instance buffer");
  11351. }
  11352. buffer.capacity = capacity;
  11353. this.bindArrayBuffer(buffer);
  11354. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  11355. return buffer;
  11356. };
  11357. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  11358. this._gl.deleteBuffer(buffer);
  11359. };
  11360. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  11361. this.bindArrayBuffer(instancesBuffer);
  11362. if (data) {
  11363. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  11364. }
  11365. if (offsetLocations[0].index !== undefined) {
  11366. var stride = 0;
  11367. for (var i = 0; i < offsetLocations.length; i++) {
  11368. var ai = offsetLocations[i];
  11369. stride += ai.attributeSize * 4;
  11370. }
  11371. for (var i = 0; i < offsetLocations.length; i++) {
  11372. var ai = offsetLocations[i];
  11373. if (!this._vertexAttribArraysEnabled[ai.index]) {
  11374. this._gl.enableVertexAttribArray(ai.index);
  11375. this._vertexAttribArraysEnabled[ai.index] = true;
  11376. }
  11377. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  11378. this._gl.vertexAttribDivisor(ai.index, 1);
  11379. this._currentInstanceLocations.push(ai.index);
  11380. this._currentInstanceBuffers.push(instancesBuffer);
  11381. }
  11382. }
  11383. else {
  11384. for (var index = 0; index < 4; index++) {
  11385. var offsetLocation = offsetLocations[index];
  11386. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  11387. this._gl.enableVertexAttribArray(offsetLocation);
  11388. this._vertexAttribArraysEnabled[offsetLocation] = true;
  11389. }
  11390. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  11391. this._gl.vertexAttribDivisor(offsetLocation, 1);
  11392. this._currentInstanceLocations.push(offsetLocation);
  11393. this._currentInstanceBuffers.push(instancesBuffer);
  11394. }
  11395. }
  11396. };
  11397. Engine.prototype.applyStates = function () {
  11398. this._depthCullingState.apply(this._gl);
  11399. this._stencilState.apply(this._gl);
  11400. this._alphaState.apply(this._gl);
  11401. };
  11402. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  11403. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  11404. };
  11405. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  11406. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  11407. };
  11408. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  11409. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  11410. };
  11411. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  11412. // Apply states
  11413. this.applyStates();
  11414. this._drawCalls.addCount(1, false);
  11415. // Render
  11416. var drawMode = this.DrawMode(fillMode);
  11417. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  11418. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  11419. if (instancesCount) {
  11420. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  11421. }
  11422. else {
  11423. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  11424. }
  11425. };
  11426. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  11427. // Apply states
  11428. this.applyStates();
  11429. this._drawCalls.addCount(1, false);
  11430. var drawMode = this.DrawMode(fillMode);
  11431. if (instancesCount) {
  11432. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  11433. }
  11434. else {
  11435. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  11436. }
  11437. };
  11438. Engine.prototype.DrawMode = function (fillMode) {
  11439. switch (fillMode) {
  11440. // Triangle views
  11441. case BABYLON.Material.TriangleFillMode:
  11442. return this._gl.TRIANGLES;
  11443. case BABYLON.Material.PointFillMode:
  11444. return this._gl.POINTS;
  11445. case BABYLON.Material.WireFrameFillMode:
  11446. return this._gl.LINES;
  11447. // Draw modes
  11448. case BABYLON.Material.PointListDrawMode:
  11449. return this._gl.POINTS;
  11450. case BABYLON.Material.LineListDrawMode:
  11451. return this._gl.LINES;
  11452. case BABYLON.Material.LineLoopDrawMode:
  11453. return this._gl.LINE_LOOP;
  11454. case BABYLON.Material.LineStripDrawMode:
  11455. return this._gl.LINE_STRIP;
  11456. case BABYLON.Material.TriangleStripDrawMode:
  11457. return this._gl.TRIANGLE_STRIP;
  11458. case BABYLON.Material.TriangleFanDrawMode:
  11459. return this._gl.TRIANGLE_FAN;
  11460. default:
  11461. return this._gl.TRIANGLES;
  11462. }
  11463. };
  11464. // Shaders
  11465. Engine.prototype._releaseEffect = function (effect) {
  11466. if (this._compiledEffects[effect._key]) {
  11467. delete this._compiledEffects[effect._key];
  11468. this._deleteProgram(effect.getProgram());
  11469. }
  11470. };
  11471. Engine.prototype._deleteProgram = function (program) {
  11472. if (program) {
  11473. program.__SPECTOR_rebuildProgram = null;
  11474. if (program.transformFeedback) {
  11475. this.deleteTransformFeedback(program.transformFeedback);
  11476. program.transformFeedback = null;
  11477. }
  11478. this._gl.deleteProgram(program);
  11479. }
  11480. };
  11481. /**
  11482. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  11483. * @param samplers An array of string used to represent textures
  11484. */
  11485. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  11486. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  11487. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  11488. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  11489. if (this._compiledEffects[name]) {
  11490. var compiledEffect = this._compiledEffects[name];
  11491. if (onCompiled && compiledEffect.isReady()) {
  11492. onCompiled(compiledEffect);
  11493. }
  11494. return compiledEffect;
  11495. }
  11496. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  11497. effect._key = name;
  11498. this._compiledEffects[name] = effect;
  11499. return effect;
  11500. };
  11501. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  11502. if (uniformsNames === void 0) { uniformsNames = []; }
  11503. if (samplers === void 0) { samplers = []; }
  11504. if (defines === void 0) { defines = ""; }
  11505. return this.createEffect({
  11506. vertex: "particles",
  11507. fragmentElement: fragmentName
  11508. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  11509. };
  11510. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  11511. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  11512. context = context || this._gl;
  11513. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  11514. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  11515. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  11516. };
  11517. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  11518. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  11519. context = context || this._gl;
  11520. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  11521. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  11522. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  11523. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  11524. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  11525. this.onAfterShaderCompilationObservable.notifyObservers(this);
  11526. return program;
  11527. };
  11528. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  11529. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  11530. var shaderProgram = context.createProgram();
  11531. if (!shaderProgram) {
  11532. throw new Error("Unable to create program");
  11533. }
  11534. context.attachShader(shaderProgram, vertexShader);
  11535. context.attachShader(shaderProgram, fragmentShader);
  11536. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  11537. var transformFeedback = this.createTransformFeedback();
  11538. this.bindTransformFeedback(transformFeedback);
  11539. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  11540. shaderProgram.transformFeedback = transformFeedback;
  11541. }
  11542. context.linkProgram(shaderProgram);
  11543. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  11544. this.bindTransformFeedback(null);
  11545. }
  11546. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  11547. if (!linked) {
  11548. context.validateProgram(shaderProgram);
  11549. var error = context.getProgramInfoLog(shaderProgram);
  11550. if (error) {
  11551. throw new Error(error);
  11552. }
  11553. }
  11554. context.deleteShader(vertexShader);
  11555. context.deleteShader(fragmentShader);
  11556. return shaderProgram;
  11557. };
  11558. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  11559. var results = new Array();
  11560. for (var index = 0; index < uniformsNames.length; index++) {
  11561. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  11562. }
  11563. return results;
  11564. };
  11565. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  11566. var results = [];
  11567. for (var index = 0; index < attributesNames.length; index++) {
  11568. try {
  11569. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  11570. }
  11571. catch (e) {
  11572. results.push(-1);
  11573. }
  11574. }
  11575. return results;
  11576. };
  11577. Engine.prototype.enableEffect = function (effect) {
  11578. if (!effect) {
  11579. return;
  11580. }
  11581. // Use program
  11582. this.bindSamplers(effect);
  11583. this._currentEffect = effect;
  11584. if (effect.onBind) {
  11585. effect.onBind(effect);
  11586. }
  11587. effect.onBindObservable.notifyObservers(effect);
  11588. };
  11589. Engine.prototype.setIntArray = function (uniform, array) {
  11590. if (!uniform)
  11591. return;
  11592. this._gl.uniform1iv(uniform, array);
  11593. };
  11594. Engine.prototype.setIntArray2 = function (uniform, array) {
  11595. if (!uniform || array.length % 2 !== 0)
  11596. return;
  11597. this._gl.uniform2iv(uniform, array);
  11598. };
  11599. Engine.prototype.setIntArray3 = function (uniform, array) {
  11600. if (!uniform || array.length % 3 !== 0)
  11601. return;
  11602. this._gl.uniform3iv(uniform, array);
  11603. };
  11604. Engine.prototype.setIntArray4 = function (uniform, array) {
  11605. if (!uniform || array.length % 4 !== 0)
  11606. return;
  11607. this._gl.uniform4iv(uniform, array);
  11608. };
  11609. Engine.prototype.setFloatArray = function (uniform, array) {
  11610. if (!uniform)
  11611. return;
  11612. this._gl.uniform1fv(uniform, array);
  11613. };
  11614. Engine.prototype.setFloatArray2 = function (uniform, array) {
  11615. if (!uniform || array.length % 2 !== 0)
  11616. return;
  11617. this._gl.uniform2fv(uniform, array);
  11618. };
  11619. Engine.prototype.setFloatArray3 = function (uniform, array) {
  11620. if (!uniform || array.length % 3 !== 0)
  11621. return;
  11622. this._gl.uniform3fv(uniform, array);
  11623. };
  11624. Engine.prototype.setFloatArray4 = function (uniform, array) {
  11625. if (!uniform || array.length % 4 !== 0)
  11626. return;
  11627. this._gl.uniform4fv(uniform, array);
  11628. };
  11629. Engine.prototype.setArray = function (uniform, array) {
  11630. if (!uniform)
  11631. return;
  11632. this._gl.uniform1fv(uniform, array);
  11633. };
  11634. Engine.prototype.setArray2 = function (uniform, array) {
  11635. if (!uniform || array.length % 2 !== 0)
  11636. return;
  11637. this._gl.uniform2fv(uniform, array);
  11638. };
  11639. Engine.prototype.setArray3 = function (uniform, array) {
  11640. if (!uniform || array.length % 3 !== 0)
  11641. return;
  11642. this._gl.uniform3fv(uniform, array);
  11643. };
  11644. Engine.prototype.setArray4 = function (uniform, array) {
  11645. if (!uniform || array.length % 4 !== 0)
  11646. return;
  11647. this._gl.uniform4fv(uniform, array);
  11648. };
  11649. Engine.prototype.setMatrices = function (uniform, matrices) {
  11650. if (!uniform)
  11651. return;
  11652. this._gl.uniformMatrix4fv(uniform, false, matrices);
  11653. };
  11654. Engine.prototype.setMatrix = function (uniform, matrix) {
  11655. if (!uniform)
  11656. return;
  11657. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  11658. };
  11659. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  11660. if (!uniform)
  11661. return;
  11662. this._gl.uniformMatrix3fv(uniform, false, matrix);
  11663. };
  11664. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  11665. if (!uniform)
  11666. return;
  11667. this._gl.uniformMatrix2fv(uniform, false, matrix);
  11668. };
  11669. Engine.prototype.setInt = function (uniform, value) {
  11670. if (!uniform)
  11671. return;
  11672. this._gl.uniform1i(uniform, value);
  11673. };
  11674. Engine.prototype.setFloat = function (uniform, value) {
  11675. if (!uniform)
  11676. return;
  11677. this._gl.uniform1f(uniform, value);
  11678. };
  11679. Engine.prototype.setFloat2 = function (uniform, x, y) {
  11680. if (!uniform)
  11681. return;
  11682. this._gl.uniform2f(uniform, x, y);
  11683. };
  11684. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  11685. if (!uniform)
  11686. return;
  11687. this._gl.uniform3f(uniform, x, y, z);
  11688. };
  11689. Engine.prototype.setBool = function (uniform, bool) {
  11690. if (!uniform)
  11691. return;
  11692. this._gl.uniform1i(uniform, bool);
  11693. };
  11694. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  11695. if (!uniform)
  11696. return;
  11697. this._gl.uniform4f(uniform, x, y, z, w);
  11698. };
  11699. Engine.prototype.setColor3 = function (uniform, color3) {
  11700. if (!uniform)
  11701. return;
  11702. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  11703. };
  11704. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  11705. if (!uniform)
  11706. return;
  11707. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  11708. };
  11709. // States
  11710. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  11711. if (zOffset === void 0) { zOffset = 0; }
  11712. if (reverseSide === void 0) { reverseSide = false; }
  11713. // Culling
  11714. if (this._depthCullingState.cull !== culling || force) {
  11715. this._depthCullingState.cull = culling;
  11716. }
  11717. // Cull face
  11718. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  11719. if (this._depthCullingState.cullFace !== cullFace || force) {
  11720. this._depthCullingState.cullFace = cullFace;
  11721. }
  11722. // Z offset
  11723. this.setZOffset(zOffset);
  11724. // Front face
  11725. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  11726. if (this._depthCullingState.frontFace !== frontFace || force) {
  11727. this._depthCullingState.frontFace = frontFace;
  11728. }
  11729. };
  11730. Engine.prototype.setZOffset = function (value) {
  11731. this._depthCullingState.zOffset = value;
  11732. };
  11733. Engine.prototype.getZOffset = function () {
  11734. return this._depthCullingState.zOffset;
  11735. };
  11736. Engine.prototype.setDepthBuffer = function (enable) {
  11737. this._depthCullingState.depthTest = enable;
  11738. };
  11739. Engine.prototype.getDepthWrite = function () {
  11740. return this._depthCullingState.depthMask;
  11741. };
  11742. Engine.prototype.setDepthWrite = function (enable) {
  11743. this._depthCullingState.depthMask = enable;
  11744. };
  11745. Engine.prototype.setColorWrite = function (enable) {
  11746. this._gl.colorMask(enable, enable, enable, enable);
  11747. this._colorWrite = enable;
  11748. };
  11749. Engine.prototype.getColorWrite = function () {
  11750. return this._colorWrite;
  11751. };
  11752. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  11753. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  11754. };
  11755. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  11756. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  11757. if (this._alphaMode === mode) {
  11758. return;
  11759. }
  11760. switch (mode) {
  11761. case Engine.ALPHA_DISABLE:
  11762. this._alphaState.alphaBlend = false;
  11763. break;
  11764. case Engine.ALPHA_PREMULTIPLIED:
  11765. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  11766. this._alphaState.alphaBlend = true;
  11767. break;
  11768. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  11769. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  11770. this._alphaState.alphaBlend = true;
  11771. break;
  11772. case Engine.ALPHA_COMBINE:
  11773. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  11774. this._alphaState.alphaBlend = true;
  11775. break;
  11776. case Engine.ALPHA_ONEONE:
  11777. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  11778. this._alphaState.alphaBlend = true;
  11779. break;
  11780. case Engine.ALPHA_ADD:
  11781. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  11782. this._alphaState.alphaBlend = true;
  11783. break;
  11784. case Engine.ALPHA_SUBTRACT:
  11785. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  11786. this._alphaState.alphaBlend = true;
  11787. break;
  11788. case Engine.ALPHA_MULTIPLY:
  11789. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  11790. this._alphaState.alphaBlend = true;
  11791. break;
  11792. case Engine.ALPHA_MAXIMIZED:
  11793. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  11794. this._alphaState.alphaBlend = true;
  11795. break;
  11796. case Engine.ALPHA_INTERPOLATE:
  11797. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  11798. this._alphaState.alphaBlend = true;
  11799. break;
  11800. case Engine.ALPHA_SCREENMODE:
  11801. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  11802. this._alphaState.alphaBlend = true;
  11803. break;
  11804. }
  11805. if (!noDepthWriteChange) {
  11806. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  11807. }
  11808. this._alphaMode = mode;
  11809. };
  11810. Engine.prototype.getAlphaMode = function () {
  11811. return this._alphaMode;
  11812. };
  11813. // Textures
  11814. Engine.prototype.wipeCaches = function (bruteForce) {
  11815. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  11816. return;
  11817. }
  11818. this._currentEffect = null;
  11819. // 6/8/2017: deltakosh: Should not be required anymore.
  11820. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  11821. if (bruteForce) {
  11822. this.resetTextureCache();
  11823. this._currentProgram = null;
  11824. this._stencilState.reset();
  11825. this._depthCullingState.reset();
  11826. this.setDepthFunctionToLessOrEqual();
  11827. this._alphaState.reset();
  11828. }
  11829. this._resetVertexBufferBinding();
  11830. this._cachedIndexBuffer = null;
  11831. this._cachedEffectForVertexBuffers = null;
  11832. this._unbindVertexArrayObject();
  11833. this.bindIndexBuffer(null);
  11834. };
  11835. /**
  11836. * Set the compressed texture format to use, based on the formats you have, and the formats
  11837. * supported by the hardware / browser.
  11838. *
  11839. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  11840. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  11841. * to API arguments needed to compressed textures. This puts the burden on the container
  11842. * generator to house the arcane code for determining these for current & future formats.
  11843. *
  11844. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  11845. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  11846. *
  11847. * Note: The result of this call is not taken into account when a texture is base64.
  11848. *
  11849. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  11850. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  11851. *
  11852. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  11853. * @returns The extension selected.
  11854. */
  11855. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  11856. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  11857. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  11858. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  11859. return this._textureFormatInUse = this._texturesSupported[i];
  11860. }
  11861. }
  11862. }
  11863. // actively set format to nothing, to allow this to be called more than once
  11864. // and possibly fail the 2nd time
  11865. this._textureFormatInUse = null;
  11866. return null;
  11867. };
  11868. Engine.prototype._createTexture = function () {
  11869. var texture = this._gl.createTexture();
  11870. if (!texture) {
  11871. throw new Error("Unable to create texture");
  11872. }
  11873. return texture;
  11874. };
  11875. /**
  11876. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  11877. * @param {string} urlArg- This contains one of the following:
  11878. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  11879. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  11880. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  11881. *
  11882. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  11883. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  11884. * @param {Scene} scene- Needed for loading to the correct scene.
  11885. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  11886. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  11887. * @param {callback} onError- Optional callback to be called upon failure.
  11888. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  11889. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  11890. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  11891. *
  11892. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  11893. */
  11894. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  11895. var _this = this;
  11896. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11897. if (onLoad === void 0) { onLoad = null; }
  11898. if (onError === void 0) { onError = null; }
  11899. if (buffer === void 0) { buffer = null; }
  11900. if (fallBack === void 0) { fallBack = null; }
  11901. if (format === void 0) { format = null; }
  11902. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  11903. var fromData = url.substr(0, 5) === "data:";
  11904. var fromBlob = url.substr(0, 5) === "blob:";
  11905. var isBase64 = fromData && url.indexOf("base64") !== -1;
  11906. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  11907. // establish the file extension, if possible
  11908. var lastDot = url.lastIndexOf('.');
  11909. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  11910. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  11911. var isTGA = (extension.indexOf(".tga") === 0);
  11912. // determine if a ktx file should be substituted
  11913. var isKTX = false;
  11914. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  11915. url = url.substring(0, lastDot) + this._textureFormatInUse;
  11916. isKTX = true;
  11917. }
  11918. if (scene) {
  11919. scene._addPendingData(texture);
  11920. }
  11921. texture.url = url;
  11922. texture.generateMipMaps = !noMipmap;
  11923. texture.samplingMode = samplingMode;
  11924. texture.invertY = invertY;
  11925. if (!this._doNotHandleContextLost) {
  11926. // Keep a link to the buffer only if we plan to handle context lost
  11927. texture._buffer = buffer;
  11928. }
  11929. var onLoadObserver = null;
  11930. if (onLoad && !fallBack) {
  11931. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  11932. }
  11933. if (!fallBack)
  11934. this._internalTexturesCache.push(texture);
  11935. var onerror = function (message, exception) {
  11936. if (scene) {
  11937. scene._removePendingData(texture);
  11938. }
  11939. if (onLoadObserver) {
  11940. texture.onLoadedObservable.remove(onLoadObserver);
  11941. }
  11942. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  11943. if (isKTX) {
  11944. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  11945. }
  11946. else if (BABYLON.Tools.UseFallbackTexture) {
  11947. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  11948. }
  11949. if (onError) {
  11950. onError(message || "Unknown error", exception);
  11951. }
  11952. };
  11953. var callback = null;
  11954. // processing for non-image formats
  11955. if (isKTX || isTGA || isDDS) {
  11956. if (isKTX) {
  11957. callback = function (data) {
  11958. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  11959. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  11960. ktx.uploadLevels(_this._gl, !noMipmap);
  11961. return false;
  11962. }, samplingMode);
  11963. };
  11964. }
  11965. else if (isTGA) {
  11966. callback = function (arrayBuffer) {
  11967. var data = new Uint8Array(arrayBuffer);
  11968. var header = BABYLON.TGATools.GetTGAHeader(data);
  11969. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  11970. BABYLON.TGATools.UploadContent(_this._gl, data);
  11971. return false;
  11972. }, samplingMode);
  11973. };
  11974. }
  11975. else if (isDDS) {
  11976. callback = function (data) {
  11977. var info = BABYLON.DDSTools.GetDDSInfo(data);
  11978. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  11979. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  11980. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  11981. return false;
  11982. }, samplingMode);
  11983. };
  11984. }
  11985. if (!buffer) {
  11986. this._loadFile(url, function (data) {
  11987. if (callback) {
  11988. callback(data);
  11989. }
  11990. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  11991. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  11992. });
  11993. }
  11994. else {
  11995. if (callback) {
  11996. callback(buffer);
  11997. }
  11998. }
  11999. // image format processing
  12000. }
  12001. else {
  12002. var onload = function (img) {
  12003. if (fromBlob && !_this._doNotHandleContextLost) {
  12004. // We need to store the image if we need to rebuild the texture
  12005. // in case of a webgl context lost
  12006. texture._buffer = img;
  12007. }
  12008. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  12009. var gl = _this._gl;
  12010. var isPot = (img.width === potWidth && img.height === potHeight);
  12011. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  12012. if (isPot) {
  12013. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  12014. return false;
  12015. }
  12016. // Using shaders to rescale because canvas.drawImage is lossy
  12017. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  12018. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  12019. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  12020. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12021. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  12022. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12023. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12024. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  12025. _this._releaseTexture(source);
  12026. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12027. continuationCallback();
  12028. });
  12029. return true;
  12030. }, samplingMode);
  12031. };
  12032. if (!fromData || isBase64)
  12033. if (buffer instanceof HTMLImageElement) {
  12034. onload(buffer);
  12035. }
  12036. else {
  12037. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  12038. }
  12039. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  12040. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  12041. else
  12042. onload(buffer);
  12043. }
  12044. return texture;
  12045. };
  12046. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  12047. var _this = this;
  12048. var rtt = this.createRenderTargetTexture({
  12049. width: destination.width,
  12050. height: destination.height,
  12051. }, {
  12052. generateMipMaps: false,
  12053. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  12054. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  12055. generateDepthBuffer: false,
  12056. generateStencilBuffer: false
  12057. });
  12058. if (!this._rescalePostProcess) {
  12059. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  12060. }
  12061. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  12062. _this._rescalePostProcess.onApply = function (effect) {
  12063. effect._bindTexture("textureSampler", source);
  12064. };
  12065. var hostingScene = scene;
  12066. if (!hostingScene) {
  12067. hostingScene = _this.scenes[_this.scenes.length - 1];
  12068. }
  12069. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  12070. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  12071. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  12072. _this.unBindFramebuffer(rtt);
  12073. _this._releaseTexture(rtt);
  12074. if (onComplete) {
  12075. onComplete();
  12076. }
  12077. });
  12078. };
  12079. Engine.prototype._getInternalFormat = function (format) {
  12080. var internalFormat = this._gl.RGBA;
  12081. switch (format) {
  12082. case Engine.TEXTUREFORMAT_ALPHA:
  12083. internalFormat = this._gl.ALPHA;
  12084. break;
  12085. case Engine.TEXTUREFORMAT_LUMINANCE:
  12086. internalFormat = this._gl.LUMINANCE;
  12087. break;
  12088. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  12089. internalFormat = this._gl.LUMINANCE_ALPHA;
  12090. break;
  12091. case Engine.TEXTUREFORMAT_RGB:
  12092. internalFormat = this._gl.RGB;
  12093. break;
  12094. case Engine.TEXTUREFORMAT_RGBA:
  12095. internalFormat = this._gl.RGBA;
  12096. break;
  12097. }
  12098. return internalFormat;
  12099. };
  12100. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  12101. if (compression === void 0) { compression = null; }
  12102. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  12103. if (!texture) {
  12104. return;
  12105. }
  12106. var internalFormat = this._getInternalFormat(format);
  12107. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  12108. var textureType = this._getWebGLTextureType(type);
  12109. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12110. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12111. if (!this._doNotHandleContextLost) {
  12112. texture._bufferView = data;
  12113. texture.format = format;
  12114. texture.type = type;
  12115. texture.invertY = invertY;
  12116. texture._compression = compression;
  12117. }
  12118. if (texture.width % 4 !== 0) {
  12119. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  12120. }
  12121. if (compression && data) {
  12122. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  12123. }
  12124. else {
  12125. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  12126. }
  12127. if (texture.generateMipMaps) {
  12128. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12129. }
  12130. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12131. // this.resetTextureCache();
  12132. texture.isReady = true;
  12133. };
  12134. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  12135. if (compression === void 0) { compression = null; }
  12136. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  12137. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  12138. texture.baseWidth = width;
  12139. texture.baseHeight = height;
  12140. texture.width = width;
  12141. texture.height = height;
  12142. texture.format = format;
  12143. texture.generateMipMaps = generateMipMaps;
  12144. texture.samplingMode = samplingMode;
  12145. texture.invertY = invertY;
  12146. texture._compression = compression;
  12147. texture.type = type;
  12148. if (!this._doNotHandleContextLost) {
  12149. texture._bufferView = data;
  12150. }
  12151. this.updateRawTexture(texture, data, format, invertY, compression, type);
  12152. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12153. // Filters
  12154. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  12155. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12156. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12157. if (generateMipMaps) {
  12158. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12159. }
  12160. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12161. this._internalTexturesCache.push(texture);
  12162. return texture;
  12163. };
  12164. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  12165. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  12166. texture.baseWidth = width;
  12167. texture.baseHeight = height;
  12168. if (generateMipMaps) {
  12169. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  12170. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  12171. }
  12172. // this.resetTextureCache();
  12173. texture.width = width;
  12174. texture.height = height;
  12175. texture.isReady = false;
  12176. texture.generateMipMaps = generateMipMaps;
  12177. texture.samplingMode = samplingMode;
  12178. this.updateTextureSamplingMode(samplingMode, texture);
  12179. this._internalTexturesCache.push(texture);
  12180. return texture;
  12181. };
  12182. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  12183. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  12184. if (texture.isCube) {
  12185. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  12186. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12187. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12188. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12189. }
  12190. else if (texture.is3D) {
  12191. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  12192. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12193. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12194. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12195. }
  12196. else {
  12197. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12198. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12199. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12200. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12201. }
  12202. texture.samplingMode = samplingMode;
  12203. };
  12204. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  12205. if (premulAlpha === void 0) { premulAlpha = false; }
  12206. if (!texture) {
  12207. return;
  12208. }
  12209. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12210. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  12211. if (premulAlpha) {
  12212. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  12213. }
  12214. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  12215. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  12216. if (texture.generateMipMaps) {
  12217. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12218. }
  12219. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12220. if (premulAlpha) {
  12221. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  12222. }
  12223. texture.isReady = true;
  12224. };
  12225. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  12226. if (!texture || texture._isDisabled) {
  12227. return;
  12228. }
  12229. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12230. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  12231. try {
  12232. // Testing video texture support
  12233. if (this._videoTextureSupported === undefined) {
  12234. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  12235. if (this._gl.getError() !== 0) {
  12236. this._videoTextureSupported = false;
  12237. }
  12238. else {
  12239. this._videoTextureSupported = true;
  12240. }
  12241. }
  12242. // Copy video through the current working canvas if video texture is not supported
  12243. if (!this._videoTextureSupported) {
  12244. if (!texture._workingCanvas) {
  12245. texture._workingCanvas = document.createElement("canvas");
  12246. var context = texture._workingCanvas.getContext("2d");
  12247. if (!context) {
  12248. throw new Error("Unable to get 2d context");
  12249. }
  12250. texture._workingContext = context;
  12251. texture._workingCanvas.width = texture.width;
  12252. texture._workingCanvas.height = texture.height;
  12253. }
  12254. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  12255. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  12256. }
  12257. else {
  12258. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  12259. }
  12260. if (texture.generateMipMaps) {
  12261. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12262. }
  12263. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12264. // this.resetTextureCache();
  12265. texture.isReady = true;
  12266. }
  12267. catch (ex) {
  12268. // Something unexpected
  12269. // Let's disable the texture
  12270. texture._isDisabled = true;
  12271. }
  12272. };
  12273. Engine.prototype.createRenderTargetTexture = function (size, options) {
  12274. var fullOptions = new RenderTargetCreationOptions();
  12275. if (options !== undefined && typeof options === "object") {
  12276. fullOptions.generateMipMaps = options.generateMipMaps;
  12277. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  12278. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  12279. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  12280. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  12281. }
  12282. else {
  12283. fullOptions.generateMipMaps = options;
  12284. fullOptions.generateDepthBuffer = true;
  12285. fullOptions.generateStencilBuffer = false;
  12286. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  12287. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  12288. }
  12289. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  12290. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  12291. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12292. }
  12293. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  12294. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  12295. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12296. }
  12297. var gl = this._gl;
  12298. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  12299. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12300. var width = size.width || size;
  12301. var height = size.height || size;
  12302. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  12303. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  12304. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  12305. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  12306. }
  12307. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  12308. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  12309. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12310. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12311. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  12312. // Create the framebuffer
  12313. var framebuffer = gl.createFramebuffer();
  12314. this.bindUnboundFramebuffer(framebuffer);
  12315. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  12316. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  12317. if (fullOptions.generateMipMaps) {
  12318. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12319. }
  12320. // Unbind
  12321. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12322. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12323. this.bindUnboundFramebuffer(null);
  12324. texture._framebuffer = framebuffer;
  12325. texture.baseWidth = width;
  12326. texture.baseHeight = height;
  12327. texture.width = width;
  12328. texture.height = height;
  12329. texture.isReady = true;
  12330. texture.samples = 1;
  12331. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  12332. texture.samplingMode = fullOptions.samplingMode;
  12333. texture.type = fullOptions.type;
  12334. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  12335. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  12336. // this.resetTextureCache();
  12337. this._internalTexturesCache.push(texture);
  12338. return texture;
  12339. };
  12340. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  12341. var generateMipMaps = false;
  12342. var generateDepthBuffer = true;
  12343. var generateStencilBuffer = false;
  12344. var generateDepthTexture = false;
  12345. var textureCount = 1;
  12346. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  12347. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  12348. var types = [], samplingModes = [];
  12349. if (options !== undefined) {
  12350. generateMipMaps = options.generateMipMaps;
  12351. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  12352. generateStencilBuffer = options.generateStencilBuffer;
  12353. generateDepthTexture = options.generateDepthTexture;
  12354. textureCount = options.textureCount || 1;
  12355. if (options.types) {
  12356. types = options.types;
  12357. }
  12358. if (options.samplingModes) {
  12359. samplingModes = options.samplingModes;
  12360. }
  12361. }
  12362. var gl = this._gl;
  12363. // Create the framebuffer
  12364. var framebuffer = gl.createFramebuffer();
  12365. this.bindUnboundFramebuffer(framebuffer);
  12366. var width = size.width || size;
  12367. var height = size.height || size;
  12368. var textures = [];
  12369. var attachments = [];
  12370. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  12371. for (var i = 0; i < textureCount; i++) {
  12372. var samplingMode = samplingModes[i] || defaultSamplingMode;
  12373. var type = types[i] || defaultType;
  12374. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  12375. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  12376. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12377. }
  12378. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  12379. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  12380. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12381. }
  12382. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  12383. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  12384. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  12385. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  12386. }
  12387. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  12388. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12389. textures.push(texture);
  12390. attachments.push(attachment);
  12391. gl.activeTexture(gl["TEXTURE" + i]);
  12392. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  12393. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  12394. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  12395. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12396. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12397. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  12398. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  12399. if (generateMipMaps) {
  12400. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12401. }
  12402. // Unbind
  12403. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12404. texture._framebuffer = framebuffer;
  12405. texture._depthStencilBuffer = depthStencilBuffer;
  12406. texture.baseWidth = width;
  12407. texture.baseHeight = height;
  12408. texture.width = width;
  12409. texture.height = height;
  12410. texture.isReady = true;
  12411. texture.samples = 1;
  12412. texture.generateMipMaps = generateMipMaps;
  12413. texture.samplingMode = samplingMode;
  12414. texture.type = type;
  12415. texture._generateDepthBuffer = generateDepthBuffer;
  12416. texture._generateStencilBuffer = generateStencilBuffer;
  12417. texture._attachments = attachments;
  12418. this._internalTexturesCache.push(texture);
  12419. }
  12420. if (generateDepthTexture && this._caps.depthTextureExtension) {
  12421. // Depth texture
  12422. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  12423. gl.activeTexture(gl.TEXTURE0);
  12424. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  12425. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12426. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12427. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12428. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12429. 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);
  12430. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  12431. depthTexture._framebuffer = framebuffer;
  12432. depthTexture.baseWidth = width;
  12433. depthTexture.baseHeight = height;
  12434. depthTexture.width = width;
  12435. depthTexture.height = height;
  12436. depthTexture.isReady = true;
  12437. depthTexture.samples = 1;
  12438. depthTexture.generateMipMaps = generateMipMaps;
  12439. depthTexture.samplingMode = gl.NEAREST;
  12440. depthTexture._generateDepthBuffer = generateDepthBuffer;
  12441. depthTexture._generateStencilBuffer = generateStencilBuffer;
  12442. textures.push(depthTexture);
  12443. this._internalTexturesCache.push(depthTexture);
  12444. }
  12445. gl.drawBuffers(attachments);
  12446. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12447. this.bindUnboundFramebuffer(null);
  12448. this.resetTextureCache();
  12449. return textures;
  12450. };
  12451. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  12452. if (samples === void 0) { samples = 1; }
  12453. var depthStencilBuffer = null;
  12454. var gl = this._gl;
  12455. // Create the depth/stencil buffer
  12456. if (generateStencilBuffer) {
  12457. depthStencilBuffer = gl.createRenderbuffer();
  12458. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  12459. if (samples > 1) {
  12460. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  12461. }
  12462. else {
  12463. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  12464. }
  12465. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  12466. }
  12467. else if (generateDepthBuffer) {
  12468. depthStencilBuffer = gl.createRenderbuffer();
  12469. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  12470. if (samples > 1) {
  12471. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  12472. }
  12473. else {
  12474. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  12475. }
  12476. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  12477. }
  12478. return depthStencilBuffer;
  12479. };
  12480. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  12481. if (this.webGLVersion < 2 || !texture) {
  12482. return 1;
  12483. }
  12484. if (texture.samples === samples) {
  12485. return samples;
  12486. }
  12487. var gl = this._gl;
  12488. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  12489. // Dispose previous render buffers
  12490. if (texture._depthStencilBuffer) {
  12491. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  12492. texture._depthStencilBuffer = null;
  12493. }
  12494. if (texture._MSAAFramebuffer) {
  12495. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  12496. texture._MSAAFramebuffer = null;
  12497. }
  12498. if (texture._MSAARenderBuffer) {
  12499. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  12500. texture._MSAARenderBuffer = null;
  12501. }
  12502. if (samples > 1) {
  12503. var framebuffer = gl.createFramebuffer();
  12504. if (!framebuffer) {
  12505. throw new Error("Unable to create multi sampled framebuffer");
  12506. }
  12507. texture._MSAAFramebuffer = framebuffer;
  12508. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  12509. var colorRenderbuffer = gl.createRenderbuffer();
  12510. if (!colorRenderbuffer) {
  12511. throw new Error("Unable to create multi sampled framebuffer");
  12512. }
  12513. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  12514. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  12515. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  12516. texture._MSAARenderBuffer = colorRenderbuffer;
  12517. }
  12518. else {
  12519. this.bindUnboundFramebuffer(texture._framebuffer);
  12520. }
  12521. texture.samples = samples;
  12522. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  12523. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12524. this.bindUnboundFramebuffer(null);
  12525. return samples;
  12526. };
  12527. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  12528. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  12529. return 1;
  12530. }
  12531. if (textures[0].samples === samples) {
  12532. return samples;
  12533. }
  12534. var gl = this._gl;
  12535. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  12536. // Dispose previous render buffers
  12537. if (textures[0]._depthStencilBuffer) {
  12538. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  12539. textures[0]._depthStencilBuffer = null;
  12540. }
  12541. if (textures[0]._MSAAFramebuffer) {
  12542. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  12543. textures[0]._MSAAFramebuffer = null;
  12544. }
  12545. for (var i = 0; i < textures.length; i++) {
  12546. if (textures[i]._MSAARenderBuffer) {
  12547. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  12548. textures[i]._MSAARenderBuffer = null;
  12549. }
  12550. }
  12551. if (samples > 1) {
  12552. var framebuffer = gl.createFramebuffer();
  12553. if (!framebuffer) {
  12554. throw new Error("Unable to create multi sampled framebuffer");
  12555. }
  12556. this.bindUnboundFramebuffer(framebuffer);
  12557. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  12558. var attachments = [];
  12559. for (var i = 0; i < textures.length; i++) {
  12560. var texture = textures[i];
  12561. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12562. var colorRenderbuffer = gl.createRenderbuffer();
  12563. if (!colorRenderbuffer) {
  12564. throw new Error("Unable to create multi sampled framebuffer");
  12565. }
  12566. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  12567. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  12568. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  12569. texture._MSAAFramebuffer = framebuffer;
  12570. texture._MSAARenderBuffer = colorRenderbuffer;
  12571. texture.samples = samples;
  12572. texture._depthStencilBuffer = depthStencilBuffer;
  12573. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12574. attachments.push(attachment);
  12575. }
  12576. gl.drawBuffers(attachments);
  12577. }
  12578. else {
  12579. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12580. }
  12581. this.bindUnboundFramebuffer(null);
  12582. return samples;
  12583. };
  12584. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  12585. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  12586. };
  12587. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  12588. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  12589. };
  12590. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  12591. var gl = this._gl;
  12592. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  12593. var generateMipMaps = true;
  12594. var generateDepthBuffer = true;
  12595. var generateStencilBuffer = false;
  12596. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  12597. if (options !== undefined) {
  12598. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  12599. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  12600. generateStencilBuffer = (generateDepthBuffer && options.generateStencilBuffer) ? true : false;
  12601. if (options.samplingMode !== undefined) {
  12602. samplingMode = options.samplingMode;
  12603. }
  12604. }
  12605. texture.isCube = true;
  12606. texture.generateMipMaps = generateMipMaps;
  12607. texture.samples = 1;
  12608. texture.samplingMode = samplingMode;
  12609. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  12610. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12611. for (var face = 0; face < 6; face++) {
  12612. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  12613. }
  12614. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  12615. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  12616. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12617. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12618. // Create the framebuffer
  12619. var framebuffer = gl.createFramebuffer();
  12620. this.bindUnboundFramebuffer(framebuffer);
  12621. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  12622. // Mipmaps
  12623. if (texture.generateMipMaps) {
  12624. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12625. }
  12626. // Unbind
  12627. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12628. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12629. this.bindUnboundFramebuffer(null);
  12630. texture._framebuffer = framebuffer;
  12631. texture.width = size;
  12632. texture.height = size;
  12633. texture.isReady = true;
  12634. //this.resetTextureCache();
  12635. this._internalTexturesCache.push(texture);
  12636. return texture;
  12637. };
  12638. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  12639. var _this = this;
  12640. if (onLoad === void 0) { onLoad = null; }
  12641. if (onError === void 0) { onError = null; }
  12642. if (forcedExtension === void 0) { forcedExtension = null; }
  12643. var callback = function (loadData) {
  12644. if (!loadData) {
  12645. if (onLoad) {
  12646. onLoad(null);
  12647. }
  12648. return;
  12649. }
  12650. var texture = loadData.texture;
  12651. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  12652. texture._lodGenerationScale = scale;
  12653. texture._lodGenerationOffset = offset;
  12654. if (_this._caps.textureLOD) {
  12655. // Do not add extra process if texture lod is supported.
  12656. if (onLoad) {
  12657. onLoad(texture);
  12658. }
  12659. return;
  12660. }
  12661. var mipSlices = 3;
  12662. var gl = _this._gl;
  12663. var width = loadData.width;
  12664. if (!width) {
  12665. return;
  12666. }
  12667. var textures = [];
  12668. for (var i = 0; i < mipSlices; i++) {
  12669. //compute LOD from even spacing in smoothness (matching shader calculation)
  12670. var smoothness = i / (mipSlices - 1);
  12671. var roughness = 1 - smoothness;
  12672. var minLODIndex = offset; // roughness = 0
  12673. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  12674. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  12675. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  12676. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  12677. glTextureFromLod.isCube = true;
  12678. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  12679. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12680. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  12681. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12682. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12683. if (loadData.isDDS) {
  12684. var info = loadData.info;
  12685. var data = loadData.data;
  12686. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12687. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  12688. }
  12689. else {
  12690. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  12691. }
  12692. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12693. // Wrap in a base texture for easy binding.
  12694. var lodTexture = new BABYLON.BaseTexture(scene);
  12695. lodTexture.isCube = true;
  12696. lodTexture._texture = glTextureFromLod;
  12697. glTextureFromLod.isReady = true;
  12698. textures.push(lodTexture);
  12699. }
  12700. texture._lodTextureHigh = textures[2];
  12701. texture._lodTextureMid = textures[1];
  12702. texture._lodTextureLow = textures[0];
  12703. if (onLoad) {
  12704. onLoad(texture);
  12705. }
  12706. };
  12707. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  12708. };
  12709. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  12710. var _this = this;
  12711. if (onLoad === void 0) { onLoad = null; }
  12712. if (onError === void 0) { onError = null; }
  12713. if (forcedExtension === void 0) { forcedExtension = null; }
  12714. var gl = this._gl;
  12715. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  12716. texture.isCube = true;
  12717. texture.url = rootUrl;
  12718. texture.generateMipMaps = !noMipmap;
  12719. if (!this._doNotHandleContextLost) {
  12720. texture._extension = forcedExtension;
  12721. texture._files = files;
  12722. }
  12723. var isKTX = false;
  12724. var isDDS = false;
  12725. var lastDot = rootUrl.lastIndexOf('.');
  12726. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  12727. if (this._textureFormatInUse) {
  12728. extension = this._textureFormatInUse;
  12729. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  12730. isKTX = true;
  12731. }
  12732. else {
  12733. isDDS = (extension === ".dds");
  12734. }
  12735. var onerror = function (request, exception) {
  12736. if (onError && request) {
  12737. onError(request.status + " " + request.statusText, exception);
  12738. }
  12739. };
  12740. if (isKTX) {
  12741. this._loadFile(rootUrl, function (data) {
  12742. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  12743. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  12744. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12745. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  12746. ktx.uploadLevels(_this._gl, !noMipmap);
  12747. _this.setCubeMapTextureParams(gl, loadMipmap);
  12748. texture.width = ktx.pixelWidth;
  12749. texture.height = ktx.pixelHeight;
  12750. texture.isReady = true;
  12751. }, undefined, undefined, true, onerror);
  12752. }
  12753. else if (isDDS) {
  12754. if (files && files.length === 6) {
  12755. this._cascadeLoadFiles(rootUrl, scene, function (imgs) {
  12756. var info;
  12757. var loadMipmap = false;
  12758. var width = 0;
  12759. for (var index = 0; index < imgs.length; index++) {
  12760. var data = imgs[index];
  12761. info = BABYLON.DDSTools.GetDDSInfo(data);
  12762. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  12763. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12764. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12765. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  12766. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  12767. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12768. }
  12769. texture.width = info.width;
  12770. texture.height = info.height;
  12771. texture.type = info.textureType;
  12772. width = info.width;
  12773. }
  12774. _this.setCubeMapTextureParams(gl, loadMipmap);
  12775. texture.isReady = true;
  12776. if (onLoad) {
  12777. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  12778. }
  12779. }, files, onError);
  12780. }
  12781. else {
  12782. this._loadFile(rootUrl, function (data) {
  12783. var info = BABYLON.DDSTools.GetDDSInfo(data);
  12784. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  12785. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12786. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12787. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  12788. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  12789. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12790. }
  12791. _this.setCubeMapTextureParams(gl, loadMipmap);
  12792. texture.width = info.width;
  12793. texture.height = info.height;
  12794. texture.isReady = true;
  12795. texture.type = info.textureType;
  12796. if (onLoad) {
  12797. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  12798. }
  12799. }, undefined, undefined, true, onerror);
  12800. }
  12801. }
  12802. else {
  12803. if (!files) {
  12804. throw new Error("Cannot load cubemap because files were not defined");
  12805. }
  12806. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  12807. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  12808. var height = width;
  12809. _this._prepareWorkingCanvas();
  12810. if (!_this._workingCanvas || !_this._workingContext) {
  12811. return;
  12812. }
  12813. _this._workingCanvas.width = width;
  12814. _this._workingCanvas.height = height;
  12815. var faces = [
  12816. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  12817. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  12818. ];
  12819. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12820. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  12821. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  12822. for (var index = 0; index < faces.length; index++) {
  12823. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  12824. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  12825. }
  12826. if (!noMipmap) {
  12827. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12828. }
  12829. _this.setCubeMapTextureParams(gl, !noMipmap);
  12830. texture.width = width;
  12831. texture.height = height;
  12832. texture.isReady = true;
  12833. if (format) {
  12834. texture.format = format;
  12835. }
  12836. texture.onLoadedObservable.notifyObservers(texture);
  12837. texture.onLoadedObservable.clear();
  12838. if (onLoad) {
  12839. onLoad();
  12840. }
  12841. }, files, onError);
  12842. }
  12843. this._internalTexturesCache.push(texture);
  12844. return texture;
  12845. };
  12846. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  12847. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12848. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  12849. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12850. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12851. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12852. // this.resetTextureCache();
  12853. };
  12854. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  12855. if (compression === void 0) { compression = null; }
  12856. if (level === void 0) { level = 0; }
  12857. texture._bufferViewArray = data;
  12858. texture.format = format;
  12859. texture.type = type;
  12860. texture.invertY = invertY;
  12861. texture._compression = compression;
  12862. var gl = this._gl;
  12863. var textureType = this._getWebGLTextureType(type);
  12864. var internalFormat = this._getInternalFormat(format);
  12865. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  12866. var needConversion = false;
  12867. if (internalFormat === gl.RGB) {
  12868. internalFormat = gl.RGBA;
  12869. needConversion = true;
  12870. }
  12871. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12872. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12873. if (texture.width % 4 !== 0) {
  12874. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  12875. }
  12876. // Data are known to be in +X +Y +Z -X -Y -Z
  12877. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  12878. var faceData = data[faceIndex];
  12879. if (compression) {
  12880. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  12881. }
  12882. else {
  12883. if (needConversion) {
  12884. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  12885. }
  12886. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  12887. }
  12888. }
  12889. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  12890. if (isPot && texture.generateMipMaps && level === 0) {
  12891. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  12892. }
  12893. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12894. // this.resetTextureCache();
  12895. texture.isReady = true;
  12896. };
  12897. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  12898. if (compression === void 0) { compression = null; }
  12899. var gl = this._gl;
  12900. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  12901. texture.isCube = true;
  12902. texture.generateMipMaps = generateMipMaps;
  12903. texture.format = format;
  12904. texture.type = type;
  12905. if (!this._doNotHandleContextLost) {
  12906. texture._bufferViewArray = data;
  12907. }
  12908. var textureType = this._getWebGLTextureType(type);
  12909. var internalFormat = this._getInternalFormat(format);
  12910. if (internalFormat === gl.RGB) {
  12911. internalFormat = gl.RGBA;
  12912. }
  12913. var width = size;
  12914. var height = width;
  12915. texture.width = width;
  12916. texture.height = height;
  12917. // Double check on POT to generate Mips.
  12918. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  12919. if (!isPot) {
  12920. generateMipMaps = false;
  12921. }
  12922. // Upload data if needed. The texture won't be ready until then.
  12923. if (data) {
  12924. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  12925. }
  12926. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  12927. // Filters
  12928. if (data && generateMipMaps) {
  12929. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  12930. }
  12931. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  12932. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12933. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12934. }
  12935. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  12936. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12937. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12938. }
  12939. else {
  12940. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  12941. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  12942. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  12943. }
  12944. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12945. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12946. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12947. return texture;
  12948. };
  12949. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  12950. var _this = this;
  12951. if (onLoad === void 0) { onLoad = null; }
  12952. if (onError === void 0) { onError = null; }
  12953. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12954. if (invertY === void 0) { invertY = false; }
  12955. var gl = this._gl;
  12956. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  12957. scene._addPendingData(texture);
  12958. texture.url = url;
  12959. this._internalTexturesCache.push(texture);
  12960. var onerror = function (request, exception) {
  12961. scene._removePendingData(texture);
  12962. if (onError && request) {
  12963. onError(request.status + " " + request.statusText, exception);
  12964. }
  12965. };
  12966. var internalCallback = function (data) {
  12967. var width = texture.width;
  12968. var faceDataArrays = callback(data);
  12969. if (!faceDataArrays) {
  12970. return;
  12971. }
  12972. if (mipmmapGenerator) {
  12973. var textureType = _this._getWebGLTextureType(type);
  12974. var internalFormat = _this._getInternalFormat(format);
  12975. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  12976. var needConversion = false;
  12977. if (internalFormat === gl.RGB) {
  12978. internalFormat = gl.RGBA;
  12979. needConversion = true;
  12980. }
  12981. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12982. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  12983. var mipData = mipmmapGenerator(faceDataArrays);
  12984. for (var level = 0; level < mipData.length; level++) {
  12985. var mipSize = width >> level;
  12986. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  12987. var mipFaceData = mipData[level][faceIndex];
  12988. if (needConversion) {
  12989. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  12990. }
  12991. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  12992. }
  12993. }
  12994. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12995. }
  12996. else {
  12997. texture.generateMipMaps = !noMipmap;
  12998. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  12999. }
  13000. texture.isReady = true;
  13001. // this.resetTextureCache();
  13002. scene._removePendingData(texture);
  13003. if (onLoad) {
  13004. onLoad();
  13005. }
  13006. };
  13007. this._loadFile(url, function (data) {
  13008. internalCallback(data);
  13009. }, undefined, scene.database, true, onerror);
  13010. return texture;
  13011. };
  13012. ;
  13013. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  13014. if (compression === void 0) { compression = null; }
  13015. var internalFormat = this._getInternalFormat(format);
  13016. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13017. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13018. if (!this._doNotHandleContextLost) {
  13019. texture._bufferView = data;
  13020. texture.format = format;
  13021. texture.invertY = invertY;
  13022. texture._compression = compression;
  13023. }
  13024. if (texture.width % 4 !== 0) {
  13025. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13026. }
  13027. if (compression && data) {
  13028. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  13029. }
  13030. else {
  13031. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  13032. }
  13033. if (texture.generateMipMaps) {
  13034. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  13035. }
  13036. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13037. // this.resetTextureCache();
  13038. texture.isReady = true;
  13039. };
  13040. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  13041. if (compression === void 0) { compression = null; }
  13042. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  13043. texture.baseWidth = width;
  13044. texture.baseHeight = height;
  13045. texture.baseDepth = depth;
  13046. texture.width = width;
  13047. texture.height = height;
  13048. texture.depth = depth;
  13049. texture.format = format;
  13050. texture.generateMipMaps = generateMipMaps;
  13051. texture.samplingMode = samplingMode;
  13052. texture.is3D = true;
  13053. if (!this._doNotHandleContextLost) {
  13054. texture._bufferView = data;
  13055. }
  13056. this.updateRawTexture3D(texture, data, format, invertY, compression);
  13057. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13058. // Filters
  13059. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13060. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13061. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13062. if (generateMipMaps) {
  13063. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  13064. }
  13065. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13066. this._internalTexturesCache.push(texture);
  13067. return texture;
  13068. };
  13069. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  13070. var gl = this._gl;
  13071. if (!gl) {
  13072. return;
  13073. }
  13074. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  13075. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13076. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13077. if (!noMipmap && !isCompressed) {
  13078. gl.generateMipmap(gl.TEXTURE_2D);
  13079. }
  13080. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13081. // this.resetTextureCache();
  13082. if (scene) {
  13083. scene._removePendingData(texture);
  13084. }
  13085. texture.onLoadedObservable.notifyObservers(texture);
  13086. texture.onLoadedObservable.clear();
  13087. };
  13088. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  13089. var _this = this;
  13090. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13091. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  13092. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  13093. var gl = this._gl;
  13094. if (!gl) {
  13095. return;
  13096. }
  13097. if (!texture._webGLTexture) {
  13098. // this.resetTextureCache();
  13099. if (scene) {
  13100. scene._removePendingData(texture);
  13101. }
  13102. return;
  13103. }
  13104. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13105. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13106. texture.baseWidth = width;
  13107. texture.baseHeight = height;
  13108. texture.width = potWidth;
  13109. texture.height = potHeight;
  13110. texture.isReady = true;
  13111. if (processFunction(potWidth, potHeight, function () {
  13112. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  13113. })) {
  13114. // Returning as texture needs extra async steps
  13115. return;
  13116. }
  13117. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  13118. };
  13119. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  13120. // Create new RGBA data container.
  13121. var rgbaData;
  13122. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  13123. rgbaData = new Float32Array(width * height * 4);
  13124. }
  13125. else {
  13126. rgbaData = new Uint32Array(width * height * 4);
  13127. }
  13128. // Convert each pixel.
  13129. for (var x = 0; x < width; x++) {
  13130. for (var y = 0; y < height; y++) {
  13131. var index = (y * width + x) * 3;
  13132. var newIndex = (y * width + x) * 4;
  13133. // Map Old Value to new value.
  13134. rgbaData[newIndex + 0] = rgbData[index + 0];
  13135. rgbaData[newIndex + 1] = rgbData[index + 1];
  13136. rgbaData[newIndex + 2] = rgbData[index + 2];
  13137. // Add fully opaque alpha channel.
  13138. rgbaData[newIndex + 3] = 1;
  13139. }
  13140. }
  13141. return rgbaData;
  13142. };
  13143. Engine.prototype._releaseFramebufferObjects = function (texture) {
  13144. var gl = this._gl;
  13145. if (texture._framebuffer) {
  13146. gl.deleteFramebuffer(texture._framebuffer);
  13147. texture._framebuffer = null;
  13148. }
  13149. if (texture._depthStencilBuffer) {
  13150. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13151. texture._depthStencilBuffer = null;
  13152. }
  13153. if (texture._MSAAFramebuffer) {
  13154. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13155. texture._MSAAFramebuffer = null;
  13156. }
  13157. if (texture._MSAARenderBuffer) {
  13158. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13159. texture._MSAARenderBuffer = null;
  13160. }
  13161. };
  13162. Engine.prototype._releaseTexture = function (texture) {
  13163. var gl = this._gl;
  13164. this._releaseFramebufferObjects(texture);
  13165. gl.deleteTexture(texture._webGLTexture);
  13166. // Unbind channels
  13167. this.unbindAllTextures();
  13168. var index = this._internalTexturesCache.indexOf(texture);
  13169. if (index !== -1) {
  13170. this._internalTexturesCache.splice(index, 1);
  13171. }
  13172. // Integrated fixed lod samplers.
  13173. if (texture._lodTextureHigh) {
  13174. texture._lodTextureHigh.dispose();
  13175. }
  13176. if (texture._lodTextureMid) {
  13177. texture._lodTextureMid.dispose();
  13178. }
  13179. if (texture._lodTextureLow) {
  13180. texture._lodTextureLow.dispose();
  13181. }
  13182. };
  13183. Engine.prototype.setProgram = function (program) {
  13184. if (this._currentProgram !== program) {
  13185. this._gl.useProgram(program);
  13186. this._currentProgram = program;
  13187. }
  13188. };
  13189. Engine.prototype.bindSamplers = function (effect) {
  13190. this.setProgram(effect.getProgram());
  13191. var samplers = effect.getSamplers();
  13192. for (var index = 0; index < samplers.length; index++) {
  13193. var uniform = effect.getUniform(samplers[index]);
  13194. if (uniform) {
  13195. this._boundUniforms[index] = uniform;
  13196. }
  13197. }
  13198. this._currentEffect = null;
  13199. };
  13200. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  13201. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  13202. return;
  13203. }
  13204. // Remove
  13205. this._linkTrackers(internalTexture.previous, internalTexture.next);
  13206. // Bind last to it
  13207. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  13208. // Bind to dummy
  13209. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  13210. };
  13211. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  13212. if (!internalTexture) {
  13213. return -1;
  13214. }
  13215. internalTexture._initialSlot = channel;
  13216. if (this.disableTextureBindingOptimization) {
  13217. if (channel !== internalTexture._designatedSlot) {
  13218. this._textureCollisions.addCount(1, false);
  13219. }
  13220. }
  13221. else {
  13222. if (channel !== internalTexture._designatedSlot) {
  13223. if (internalTexture._designatedSlot > -1) {
  13224. return internalTexture._designatedSlot;
  13225. }
  13226. else {
  13227. // No slot for this texture, let's pick a new one (if we find a free slot)
  13228. if (this._nextFreeTextureSlots.length) {
  13229. return this._nextFreeTextureSlots[0];
  13230. }
  13231. // We need to recycle the oldest bound texture, sorry.
  13232. this._textureCollisions.addCount(1, false);
  13233. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  13234. }
  13235. }
  13236. }
  13237. return channel;
  13238. };
  13239. Engine.prototype._linkTrackers = function (previous, next) {
  13240. previous.next = next;
  13241. next.previous = previous;
  13242. };
  13243. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  13244. var currentSlot = internalTexture._designatedSlot;
  13245. if (currentSlot === -1) {
  13246. return -1;
  13247. }
  13248. internalTexture._designatedSlot = -1;
  13249. // Remove from bound list
  13250. this._linkTrackers(internalTexture.previous, internalTexture.next);
  13251. // Free the slot
  13252. this._boundTexturesCache[currentSlot] = null;
  13253. this._nextFreeTextureSlots.push(currentSlot);
  13254. return currentSlot;
  13255. };
  13256. Engine.prototype._activateCurrentTexture = function () {
  13257. if (this._currentTextureChannel !== this._activeChannel) {
  13258. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  13259. this._currentTextureChannel = this._activeChannel;
  13260. }
  13261. };
  13262. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  13263. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  13264. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  13265. this._activeChannel = texture._designatedSlot;
  13266. }
  13267. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  13268. var isTextureForRendering = texture && texture._initialSlot > -1;
  13269. if (currentTextureBound !== texture) {
  13270. if (currentTextureBound && !this.disableTextureBindingOptimization) {
  13271. this._removeDesignatedSlot(currentTextureBound);
  13272. }
  13273. this._activateCurrentTexture();
  13274. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  13275. this._boundTexturesCache[this._activeChannel] = texture;
  13276. if (texture) {
  13277. if (!this.disableTextureBindingOptimization) {
  13278. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  13279. if (slotIndex > -1) {
  13280. this._nextFreeTextureSlots.splice(slotIndex, 1);
  13281. }
  13282. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  13283. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  13284. }
  13285. texture._designatedSlot = this._activeChannel;
  13286. }
  13287. }
  13288. else if (forTextureDataUpdate) {
  13289. this._activateCurrentTexture();
  13290. }
  13291. if (isTextureForRendering && !forTextureDataUpdate) {
  13292. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  13293. }
  13294. };
  13295. Engine.prototype._bindTexture = function (channel, texture) {
  13296. if (channel < 0) {
  13297. return;
  13298. }
  13299. if (texture) {
  13300. channel = this._getCorrectTextureChannel(channel, texture);
  13301. }
  13302. this._activeChannel = channel;
  13303. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  13304. };
  13305. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  13306. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  13307. };
  13308. Engine.prototype.unbindAllTextures = function () {
  13309. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  13310. this._activeChannel = channel;
  13311. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13312. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13313. if (this.webGLVersion > 1) {
  13314. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13315. }
  13316. }
  13317. };
  13318. Engine.prototype.setTexture = function (channel, uniform, texture) {
  13319. if (channel < 0) {
  13320. return;
  13321. }
  13322. if (uniform) {
  13323. this._boundUniforms[channel] = uniform;
  13324. }
  13325. this._setTexture(channel, texture);
  13326. };
  13327. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  13328. var uniform = this._boundUniforms[sourceSlot];
  13329. if (uniform._currentState === destination) {
  13330. return;
  13331. }
  13332. this._gl.uniform1i(uniform, destination);
  13333. uniform._currentState = destination;
  13334. };
  13335. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  13336. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  13337. // Not ready?
  13338. if (!texture) {
  13339. if (this._boundTexturesCache[channel] != null) {
  13340. this._activeChannel = channel;
  13341. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13342. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13343. if (this.webGLVersion > 1) {
  13344. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13345. }
  13346. }
  13347. return false;
  13348. }
  13349. // Video
  13350. if (texture.video) {
  13351. this._activeChannel = channel;
  13352. texture.update();
  13353. }
  13354. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  13355. texture.delayLoad();
  13356. return false;
  13357. }
  13358. var internalTexture;
  13359. if (texture.isReady()) {
  13360. internalTexture = texture.getInternalTexture();
  13361. }
  13362. else if (texture.isCube) {
  13363. internalTexture = this.emptyCubeTexture;
  13364. }
  13365. else if (texture.is3D) {
  13366. internalTexture = this.emptyTexture3D;
  13367. }
  13368. else {
  13369. internalTexture = this.emptyTexture;
  13370. }
  13371. if (!isPartOfTextureArray) {
  13372. channel = this._getCorrectTextureChannel(channel, internalTexture);
  13373. }
  13374. if (this._boundTexturesCache[channel] === internalTexture) {
  13375. this._moveBoundTextureOnTop(internalTexture);
  13376. if (!isPartOfTextureArray) {
  13377. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  13378. }
  13379. return false;
  13380. }
  13381. this._activeChannel = channel;
  13382. if (internalTexture && internalTexture.is3D) {
  13383. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  13384. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  13385. internalTexture._cachedWrapU = texture.wrapU;
  13386. switch (texture.wrapU) {
  13387. case BABYLON.Texture.WRAP_ADDRESSMODE:
  13388. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  13389. break;
  13390. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  13391. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  13392. break;
  13393. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  13394. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  13395. break;
  13396. }
  13397. }
  13398. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  13399. internalTexture._cachedWrapV = texture.wrapV;
  13400. switch (texture.wrapV) {
  13401. case BABYLON.Texture.WRAP_ADDRESSMODE:
  13402. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  13403. break;
  13404. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  13405. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  13406. break;
  13407. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  13408. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  13409. break;
  13410. }
  13411. }
  13412. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  13413. internalTexture._cachedWrapR = texture.wrapR;
  13414. switch (texture.wrapV) {
  13415. case BABYLON.Texture.WRAP_ADDRESSMODE:
  13416. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  13417. break;
  13418. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  13419. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  13420. break;
  13421. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  13422. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  13423. break;
  13424. }
  13425. }
  13426. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  13427. }
  13428. else if (internalTexture && internalTexture.isCube) {
  13429. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  13430. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  13431. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  13432. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  13433. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  13434. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  13435. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  13436. }
  13437. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  13438. }
  13439. else {
  13440. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  13441. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  13442. internalTexture._cachedWrapU = texture.wrapU;
  13443. switch (texture.wrapU) {
  13444. case BABYLON.Texture.WRAP_ADDRESSMODE:
  13445. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  13446. break;
  13447. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  13448. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  13449. break;
  13450. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  13451. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  13452. break;
  13453. }
  13454. }
  13455. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  13456. internalTexture._cachedWrapV = texture.wrapV;
  13457. switch (texture.wrapV) {
  13458. case BABYLON.Texture.WRAP_ADDRESSMODE:
  13459. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  13460. break;
  13461. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  13462. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  13463. break;
  13464. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  13465. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  13466. break;
  13467. }
  13468. }
  13469. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  13470. }
  13471. return true;
  13472. };
  13473. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  13474. if (channel < 0 || !uniform) {
  13475. return;
  13476. }
  13477. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  13478. this._textureUnits = new Int32Array(textures.length);
  13479. }
  13480. for (var i = 0; i < textures.length; i++) {
  13481. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  13482. }
  13483. this._gl.uniform1iv(uniform, this._textureUnits);
  13484. for (var index = 0; index < textures.length; index++) {
  13485. this._setTexture(this._textureUnits[index], textures[index], true);
  13486. }
  13487. };
  13488. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  13489. var internalTexture = texture.getInternalTexture();
  13490. if (!internalTexture) {
  13491. return;
  13492. }
  13493. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  13494. var value = texture.anisotropicFilteringLevel;
  13495. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  13496. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  13497. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  13498. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  13499. }
  13500. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  13501. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  13502. internalTexture._cachedAnisotropicFilteringLevel = value;
  13503. }
  13504. };
  13505. Engine.prototype.readPixels = function (x, y, width, height) {
  13506. var data = new Uint8Array(height * width * 4);
  13507. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  13508. return data;
  13509. };
  13510. /**
  13511. * Add an externaly attached data from its key.
  13512. * This method call will fail and return false, if such key already exists.
  13513. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  13514. * @param key the unique key that identifies the data
  13515. * @param data the data object to associate to the key for this Engine instance
  13516. * @return true if no such key were already present and the data was added successfully, false otherwise
  13517. */
  13518. Engine.prototype.addExternalData = function (key, data) {
  13519. if (!this._externalData) {
  13520. this._externalData = new BABYLON.StringDictionary();
  13521. }
  13522. return this._externalData.add(key, data);
  13523. };
  13524. /**
  13525. * Get an externaly attached data from its key
  13526. * @param key the unique key that identifies the data
  13527. * @return the associated data, if present (can be null), or undefined if not present
  13528. */
  13529. Engine.prototype.getExternalData = function (key) {
  13530. if (!this._externalData) {
  13531. this._externalData = new BABYLON.StringDictionary();
  13532. }
  13533. return this._externalData.get(key);
  13534. };
  13535. /**
  13536. * Get an externaly attached data from its key, create it using a factory if it's not already present
  13537. * @param key the unique key that identifies the data
  13538. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  13539. * @return the associated data, can be null if the factory returned null.
  13540. */
  13541. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  13542. if (!this._externalData) {
  13543. this._externalData = new BABYLON.StringDictionary();
  13544. }
  13545. return this._externalData.getOrAddWithFactory(key, factory);
  13546. };
  13547. /**
  13548. * Remove an externaly attached data from the Engine instance
  13549. * @param key the unique key that identifies the data
  13550. * @return true if the data was successfully removed, false if it doesn't exist
  13551. */
  13552. Engine.prototype.removeExternalData = function (key) {
  13553. if (!this._externalData) {
  13554. this._externalData = new BABYLON.StringDictionary();
  13555. }
  13556. return this._externalData.remove(key);
  13557. };
  13558. Engine.prototype.unbindAllAttributes = function () {
  13559. if (this._mustWipeVertexAttributes) {
  13560. this._mustWipeVertexAttributes = false;
  13561. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  13562. this._gl.disableVertexAttribArray(i);
  13563. this._vertexAttribArraysEnabled[i] = false;
  13564. this._currentBufferPointers[i].active = false;
  13565. }
  13566. return;
  13567. }
  13568. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  13569. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  13570. continue;
  13571. }
  13572. this._gl.disableVertexAttribArray(i);
  13573. this._vertexAttribArraysEnabled[i] = false;
  13574. this._currentBufferPointers[i].active = false;
  13575. }
  13576. };
  13577. Engine.prototype.releaseEffects = function () {
  13578. for (var name in this._compiledEffects) {
  13579. this._deleteProgram(this._compiledEffects[name]._program);
  13580. }
  13581. this._compiledEffects = {};
  13582. };
  13583. // Dispose
  13584. Engine.prototype.dispose = function () {
  13585. this.hideLoadingUI();
  13586. this.stopRenderLoop();
  13587. // Release postProcesses
  13588. while (this.postProcesses.length) {
  13589. this.postProcesses[0].dispose();
  13590. }
  13591. // Empty texture
  13592. if (this._emptyTexture) {
  13593. this._releaseTexture(this._emptyTexture);
  13594. this._emptyTexture = null;
  13595. }
  13596. if (this._emptyCubeTexture) {
  13597. this._releaseTexture(this._emptyCubeTexture);
  13598. this._emptyCubeTexture = null;
  13599. }
  13600. // Rescale PP
  13601. if (this._rescalePostProcess) {
  13602. this._rescalePostProcess.dispose();
  13603. }
  13604. // Release scenes
  13605. while (this.scenes.length) {
  13606. this.scenes[0].dispose();
  13607. }
  13608. // Release audio engine
  13609. if (Engine.audioEngine) {
  13610. Engine.audioEngine.dispose();
  13611. }
  13612. // Release effects
  13613. this.releaseEffects();
  13614. // Unbind
  13615. this.unbindAllAttributes();
  13616. if (this._dummyFramebuffer) {
  13617. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  13618. }
  13619. //WebVR
  13620. this.disableVR();
  13621. // Events
  13622. if (BABYLON.Tools.IsWindowObjectExist()) {
  13623. window.removeEventListener("blur", this._onBlur);
  13624. window.removeEventListener("focus", this._onFocus);
  13625. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  13626. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  13627. if (this._renderingCanvas) {
  13628. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  13629. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  13630. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  13631. if (!this._doNotHandleContextLost) {
  13632. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  13633. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  13634. }
  13635. }
  13636. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  13637. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  13638. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  13639. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  13640. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  13641. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  13642. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  13643. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  13644. if (this._onVrDisplayConnect) {
  13645. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13646. if (this._onVrDisplayDisconnect) {
  13647. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13648. }
  13649. if (this._onVrDisplayPresentChange) {
  13650. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13651. }
  13652. this._onVrDisplayConnect = null;
  13653. this._onVrDisplayDisconnect = null;
  13654. }
  13655. }
  13656. // Remove from Instances
  13657. var index = Engine.Instances.indexOf(this);
  13658. if (index >= 0) {
  13659. Engine.Instances.splice(index, 1);
  13660. }
  13661. this._workingCanvas = null;
  13662. this._workingContext = null;
  13663. this._currentBufferPointers = [];
  13664. this._renderingCanvas = null;
  13665. this._currentProgram = null;
  13666. this.onResizeObservable.clear();
  13667. this.onCanvasBlurObservable.clear();
  13668. this.onCanvasFocusObservable.clear();
  13669. this.onCanvasPointerOutObservable.clear();
  13670. this.onBeginFrameObservable.clear();
  13671. this.onEndFrameObservable.clear();
  13672. BABYLON.Effect.ResetCache();
  13673. // Abort active requests
  13674. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  13675. var request = _a[_i];
  13676. request.abort();
  13677. }
  13678. };
  13679. // Loading screen
  13680. Engine.prototype.displayLoadingUI = function () {
  13681. if (!BABYLON.Tools.IsWindowObjectExist()) {
  13682. return;
  13683. }
  13684. var loadingScreen = this.loadingScreen;
  13685. if (loadingScreen) {
  13686. loadingScreen.displayLoadingUI();
  13687. }
  13688. };
  13689. Engine.prototype.hideLoadingUI = function () {
  13690. if (!BABYLON.Tools.IsWindowObjectExist()) {
  13691. return;
  13692. }
  13693. var loadingScreen = this.loadingScreen;
  13694. if (loadingScreen) {
  13695. loadingScreen.hideLoadingUI();
  13696. }
  13697. };
  13698. Object.defineProperty(Engine.prototype, "loadingScreen", {
  13699. get: function () {
  13700. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  13701. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  13702. return this._loadingScreen;
  13703. },
  13704. set: function (loadingScreen) {
  13705. this._loadingScreen = loadingScreen;
  13706. },
  13707. enumerable: true,
  13708. configurable: true
  13709. });
  13710. Object.defineProperty(Engine.prototype, "loadingUIText", {
  13711. set: function (text) {
  13712. this.loadingScreen.loadingUIText = text;
  13713. },
  13714. enumerable: true,
  13715. configurable: true
  13716. });
  13717. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  13718. set: function (color) {
  13719. this.loadingScreen.loadingUIBackgroundColor = color;
  13720. },
  13721. enumerable: true,
  13722. configurable: true
  13723. });
  13724. Engine.prototype.attachContextLostEvent = function (callback) {
  13725. if (this._renderingCanvas) {
  13726. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  13727. }
  13728. };
  13729. Engine.prototype.attachContextRestoredEvent = function (callback) {
  13730. if (this._renderingCanvas) {
  13731. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  13732. }
  13733. };
  13734. Engine.prototype.getVertexShaderSource = function (program) {
  13735. var shaders = this._gl.getAttachedShaders(program);
  13736. if (!shaders) {
  13737. return null;
  13738. }
  13739. return this._gl.getShaderSource(shaders[0]);
  13740. };
  13741. Engine.prototype.getFragmentShaderSource = function (program) {
  13742. var shaders = this._gl.getAttachedShaders(program);
  13743. if (!shaders) {
  13744. return null;
  13745. }
  13746. return this._gl.getShaderSource(shaders[1]);
  13747. };
  13748. Engine.prototype.getError = function () {
  13749. return this._gl.getError();
  13750. };
  13751. // FPS
  13752. Engine.prototype.getFps = function () {
  13753. return this._fps;
  13754. };
  13755. Engine.prototype.getDeltaTime = function () {
  13756. return this._deltaTime;
  13757. };
  13758. Engine.prototype._measureFps = function () {
  13759. this._performanceMonitor.sampleFrame();
  13760. this._fps = this._performanceMonitor.averageFPS;
  13761. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  13762. };
  13763. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  13764. if (faceIndex === void 0) { faceIndex = -1; }
  13765. var gl = this._gl;
  13766. if (!this._dummyFramebuffer) {
  13767. var dummy = gl.createFramebuffer();
  13768. if (!dummy) {
  13769. throw new Error("Unable to create dummy framebuffer");
  13770. }
  13771. this._dummyFramebuffer = dummy;
  13772. }
  13773. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  13774. if (faceIndex > -1) {
  13775. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  13776. }
  13777. else {
  13778. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13779. }
  13780. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  13781. var buffer;
  13782. switch (readType) {
  13783. case gl.UNSIGNED_BYTE:
  13784. buffer = new Uint8Array(4 * width * height);
  13785. readType = gl.UNSIGNED_BYTE;
  13786. break;
  13787. default:
  13788. buffer = new Float32Array(4 * width * height);
  13789. readType = gl.FLOAT;
  13790. break;
  13791. }
  13792. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  13793. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  13794. return buffer;
  13795. };
  13796. Engine.prototype._canRenderToFloatFramebuffer = function () {
  13797. if (this._webGLVersion > 1) {
  13798. return this._caps.colorBufferFloat;
  13799. }
  13800. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  13801. };
  13802. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  13803. if (this._webGLVersion > 1) {
  13804. return this._caps.colorBufferFloat;
  13805. }
  13806. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  13807. };
  13808. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  13809. Engine.prototype._canRenderToFramebuffer = function (type) {
  13810. var gl = this._gl;
  13811. //clear existing errors
  13812. while (gl.getError() !== gl.NO_ERROR) { }
  13813. var successful = true;
  13814. var texture = gl.createTexture();
  13815. gl.bindTexture(gl.TEXTURE_2D, texture);
  13816. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13817. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13818. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13819. var fb = gl.createFramebuffer();
  13820. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  13821. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  13822. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  13823. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  13824. successful = successful && (gl.getError() === gl.NO_ERROR);
  13825. //try render by clearing frame buffer's color buffer
  13826. if (successful) {
  13827. gl.clear(gl.COLOR_BUFFER_BIT);
  13828. successful = successful && (gl.getError() === gl.NO_ERROR);
  13829. }
  13830. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  13831. if (successful) {
  13832. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  13833. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13834. var readFormat = gl.RGBA;
  13835. var readType = gl.UNSIGNED_BYTE;
  13836. var buffer = new Uint8Array(4);
  13837. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  13838. successful = successful && (gl.getError() === gl.NO_ERROR);
  13839. }
  13840. //clean up
  13841. gl.deleteTexture(texture);
  13842. gl.deleteFramebuffer(fb);
  13843. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13844. //clear accumulated errors
  13845. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  13846. return successful;
  13847. };
  13848. Engine.prototype._getWebGLTextureType = function (type) {
  13849. if (type === Engine.TEXTURETYPE_FLOAT) {
  13850. return this._gl.FLOAT;
  13851. }
  13852. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13853. // Add Half Float Constant.
  13854. return this._gl.HALF_FLOAT_OES;
  13855. }
  13856. return this._gl.UNSIGNED_BYTE;
  13857. };
  13858. ;
  13859. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  13860. if (this._webGLVersion === 1) {
  13861. return this._gl.RGBA;
  13862. }
  13863. if (type === Engine.TEXTURETYPE_FLOAT) {
  13864. return this._gl.RGBA32F;
  13865. }
  13866. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13867. return this._gl.RGBA16F;
  13868. }
  13869. return this._gl.RGBA;
  13870. };
  13871. ;
  13872. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  13873. if (type === Engine.TEXTURETYPE_FLOAT) {
  13874. return this._gl.RGBA32F;
  13875. }
  13876. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13877. return this._gl.RGBA16F;
  13878. }
  13879. return this._gl.RGBA8;
  13880. };
  13881. ;
  13882. Engine.prototype.createQuery = function () {
  13883. return this._gl.createQuery();
  13884. };
  13885. Engine.prototype.deleteQuery = function (query) {
  13886. this._gl.deleteQuery(query);
  13887. return this;
  13888. };
  13889. Engine.prototype.isQueryResultAvailable = function (query) {
  13890. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  13891. };
  13892. Engine.prototype.getQueryResult = function (query) {
  13893. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  13894. };
  13895. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  13896. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  13897. this._gl.beginQuery(glAlgorithm, query);
  13898. return this;
  13899. };
  13900. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  13901. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  13902. this._gl.endQuery(glAlgorithm);
  13903. return this;
  13904. };
  13905. /* Time queries */
  13906. Engine.prototype._createTimeQuery = function () {
  13907. var timerQuery = this._caps.timerQuery;
  13908. if (timerQuery.createQueryEXT) {
  13909. return timerQuery.createQueryEXT();
  13910. }
  13911. return this.createQuery();
  13912. };
  13913. Engine.prototype._deleteTimeQuery = function (query) {
  13914. var timerQuery = this._caps.timerQuery;
  13915. if (timerQuery.deleteQueryEXT) {
  13916. timerQuery.deleteQueryEXT(query);
  13917. return;
  13918. }
  13919. this.deleteQuery(query);
  13920. };
  13921. Engine.prototype._getTimeQueryResult = function (query) {
  13922. var timerQuery = this._caps.timerQuery;
  13923. if (timerQuery.getQueryObjectEXT) {
  13924. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  13925. }
  13926. return this.getQueryResult(query);
  13927. };
  13928. Engine.prototype._getTimeQueryAvailability = function (query) {
  13929. var timerQuery = this._caps.timerQuery;
  13930. if (timerQuery.getQueryObjectEXT) {
  13931. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  13932. }
  13933. return this.isQueryResultAvailable(query);
  13934. };
  13935. Engine.prototype.startTimeQuery = function () {
  13936. var timerQuery = this._caps.timerQuery;
  13937. if (!timerQuery) {
  13938. return null;
  13939. }
  13940. var token = new BABYLON._TimeToken();
  13941. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  13942. if (this._caps.canUseTimestampForTimerQuery) {
  13943. token._startTimeQuery = this._createTimeQuery();
  13944. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  13945. }
  13946. else {
  13947. if (this._currentNonTimestampToken) {
  13948. return this._currentNonTimestampToken;
  13949. }
  13950. token._timeElapsedQuery = this._createTimeQuery();
  13951. if (timerQuery.beginQueryEXT) {
  13952. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  13953. }
  13954. else {
  13955. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  13956. }
  13957. this._currentNonTimestampToken = token;
  13958. }
  13959. return token;
  13960. };
  13961. Engine.prototype.endTimeQuery = function (token) {
  13962. var timerQuery = this._caps.timerQuery;
  13963. if (!timerQuery || !token) {
  13964. return -1;
  13965. }
  13966. if (this._caps.canUseTimestampForTimerQuery) {
  13967. if (!token._startTimeQuery) {
  13968. return -1;
  13969. }
  13970. if (!token._endTimeQuery) {
  13971. token._endTimeQuery = this._createTimeQuery();
  13972. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  13973. }
  13974. }
  13975. else if (!token._timeElapsedQueryEnded) {
  13976. if (!token._timeElapsedQuery) {
  13977. return -1;
  13978. }
  13979. if (timerQuery.endQueryEXT) {
  13980. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  13981. }
  13982. else {
  13983. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  13984. }
  13985. token._timeElapsedQueryEnded = true;
  13986. }
  13987. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  13988. var available = false;
  13989. if (token._endTimeQuery) {
  13990. available = this._getTimeQueryAvailability(token._endTimeQuery);
  13991. }
  13992. else if (token._timeElapsedQuery) {
  13993. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  13994. }
  13995. if (available && !disjoint) {
  13996. var result = 0;
  13997. if (this._caps.canUseTimestampForTimerQuery) {
  13998. if (!token._startTimeQuery || !token._endTimeQuery) {
  13999. return -1;
  14000. }
  14001. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  14002. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  14003. result = timeEnd - timeStart;
  14004. this._deleteTimeQuery(token._startTimeQuery);
  14005. this._deleteTimeQuery(token._endTimeQuery);
  14006. token._startTimeQuery = null;
  14007. token._endTimeQuery = null;
  14008. }
  14009. else {
  14010. if (!token._timeElapsedQuery) {
  14011. return -1;
  14012. }
  14013. result = this._getTimeQueryResult(token._timeElapsedQuery);
  14014. this._deleteTimeQuery(token._timeElapsedQuery);
  14015. token._timeElapsedQuery = null;
  14016. token._timeElapsedQueryEnded = false;
  14017. this._currentNonTimestampToken = null;
  14018. }
  14019. return result;
  14020. }
  14021. return -1;
  14022. };
  14023. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  14024. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  14025. };
  14026. // Transform feedback
  14027. Engine.prototype.createTransformFeedback = function () {
  14028. return this._gl.createTransformFeedback();
  14029. };
  14030. Engine.prototype.deleteTransformFeedback = function (value) {
  14031. this._gl.deleteTransformFeedback(value);
  14032. };
  14033. Engine.prototype.bindTransformFeedback = function (value) {
  14034. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  14035. };
  14036. Engine.prototype.beginTransformFeedback = function (usePoints) {
  14037. if (usePoints === void 0) { usePoints = true; }
  14038. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  14039. };
  14040. Engine.prototype.endTransformFeedback = function () {
  14041. this._gl.endTransformFeedback();
  14042. };
  14043. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  14044. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  14045. };
  14046. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  14047. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  14048. };
  14049. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  14050. var _this = this;
  14051. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  14052. this._activeRequests.push(request);
  14053. request.onCompleteObservable.add(function (request) {
  14054. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  14055. });
  14056. return request;
  14057. };
  14058. /** @ignore */
  14059. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  14060. var _this = this;
  14061. return new Promise(function (resolve, reject) {
  14062. _this._loadFile(url, function (data) {
  14063. resolve(data);
  14064. }, undefined, database, useArrayBuffer, function (request, exception) {
  14065. reject(exception);
  14066. });
  14067. });
  14068. };
  14069. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  14070. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14071. var onload = function (data) {
  14072. loadedFiles[index] = data;
  14073. loadedFiles._internalCount++;
  14074. if (loadedFiles._internalCount === 6) {
  14075. onfinish(loadedFiles);
  14076. }
  14077. };
  14078. var onerror = function (request, exception) {
  14079. if (onErrorCallBack && request) {
  14080. onErrorCallBack(request.status + " " + request.statusText, exception);
  14081. }
  14082. };
  14083. this._loadFile(url, onload, undefined, undefined, true, onerror);
  14084. };
  14085. Engine.prototype._cascadeLoadFiles = function (rootUrl, scene, onfinish, files, onError) {
  14086. if (onError === void 0) { onError = null; }
  14087. var loadedFiles = [];
  14088. loadedFiles._internalCount = 0;
  14089. for (var index = 0; index < 6; index++) {
  14090. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  14091. }
  14092. };
  14093. // Statics
  14094. Engine.isSupported = function () {
  14095. try {
  14096. var tempcanvas = document.createElement("canvas");
  14097. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  14098. return gl != null && !!window.WebGLRenderingContext;
  14099. }
  14100. catch (e) {
  14101. return false;
  14102. }
  14103. };
  14104. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  14105. Engine.ExceptionList = [
  14106. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  14107. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  14108. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  14109. ];
  14110. Engine.Instances = new Array();
  14111. // Const statics
  14112. Engine._ALPHA_DISABLE = 0;
  14113. Engine._ALPHA_ADD = 1;
  14114. Engine._ALPHA_COMBINE = 2;
  14115. Engine._ALPHA_SUBTRACT = 3;
  14116. Engine._ALPHA_MULTIPLY = 4;
  14117. Engine._ALPHA_MAXIMIZED = 5;
  14118. Engine._ALPHA_ONEONE = 6;
  14119. Engine._ALPHA_PREMULTIPLIED = 7;
  14120. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  14121. Engine._ALPHA_INTERPOLATE = 9;
  14122. Engine._ALPHA_SCREENMODE = 10;
  14123. Engine._DELAYLOADSTATE_NONE = 0;
  14124. Engine._DELAYLOADSTATE_LOADED = 1;
  14125. Engine._DELAYLOADSTATE_LOADING = 2;
  14126. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  14127. Engine._TEXTUREFORMAT_ALPHA = 0;
  14128. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  14129. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  14130. Engine._TEXTUREFORMAT_RGB = 4;
  14131. Engine._TEXTUREFORMAT_RGBA = 5;
  14132. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  14133. Engine._TEXTURETYPE_FLOAT = 1;
  14134. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  14135. // Depht or Stencil test Constants.
  14136. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  14137. 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.
  14138. 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.
  14139. 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.
  14140. 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.
  14141. 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.
  14142. 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.
  14143. 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.
  14144. // Stencil Actions Constants.
  14145. Engine._KEEP = 0x1E00;
  14146. Engine._REPLACE = 0x1E01;
  14147. Engine._INCR = 0x1E02;
  14148. Engine._DECR = 0x1E03;
  14149. Engine._INVERT = 0x150A;
  14150. Engine._INCR_WRAP = 0x8507;
  14151. Engine._DECR_WRAP = 0x8508;
  14152. // Texture rescaling mode
  14153. Engine._SCALEMODE_FLOOR = 1;
  14154. Engine._SCALEMODE_NEAREST = 2;
  14155. Engine._SCALEMODE_CEILING = 3;
  14156. // Updatable statics so stick with vars here
  14157. Engine.CollisionsEpsilon = 0.001;
  14158. Engine.CodeRepository = "src/";
  14159. Engine.ShadersRepository = "src/Shaders/";
  14160. return Engine;
  14161. }());
  14162. BABYLON.Engine = Engine;
  14163. })(BABYLON || (BABYLON = {}));
  14164. //# sourceMappingURL=babylon.engine.js.map
  14165. var BABYLON;
  14166. (function (BABYLON) {
  14167. /**
  14168. * Node is the basic class for all scene objects (Mesh, Light Camera).
  14169. */
  14170. var Node = /** @class */ (function () {
  14171. /**
  14172. * @constructor
  14173. * @param {string} name - the name and id to be given to this node
  14174. * @param {BABYLON.Scene} the scene this node will be added to
  14175. */
  14176. function Node(name, scene) {
  14177. if (scene === void 0) { scene = null; }
  14178. this.state = "";
  14179. this.metadata = null;
  14180. this.doNotSerialize = false;
  14181. this.animations = new Array();
  14182. this._ranges = {};
  14183. this._isEnabled = true;
  14184. this._isReady = true;
  14185. this._currentRenderId = -1;
  14186. this._parentRenderId = -1;
  14187. /**
  14188. * An event triggered when the mesh is disposed.
  14189. * @type {BABYLON.Observable}
  14190. */
  14191. this.onDisposeObservable = new BABYLON.Observable();
  14192. // Behaviors
  14193. this._behaviors = new Array();
  14194. this.name = name;
  14195. this.id = name;
  14196. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  14197. this.uniqueId = this._scene.getUniqueId();
  14198. this._initCache();
  14199. }
  14200. Object.defineProperty(Node.prototype, "parent", {
  14201. get: function () {
  14202. return this._parentNode;
  14203. },
  14204. set: function (parent) {
  14205. if (this._parentNode === parent) {
  14206. return;
  14207. }
  14208. // Remove self from list of children of parent
  14209. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  14210. var index = this._parentNode._children.indexOf(this);
  14211. if (index !== -1) {
  14212. this._parentNode._children.splice(index, 1);
  14213. }
  14214. }
  14215. // Store new parent
  14216. this._parentNode = parent;
  14217. // Add as child to new parent
  14218. if (this._parentNode) {
  14219. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  14220. this._parentNode._children = new Array();
  14221. }
  14222. this._parentNode._children.push(this);
  14223. }
  14224. },
  14225. enumerable: true,
  14226. configurable: true
  14227. });
  14228. Node.prototype.getClassName = function () {
  14229. return "Node";
  14230. };
  14231. Object.defineProperty(Node.prototype, "onDispose", {
  14232. set: function (callback) {
  14233. if (this._onDisposeObserver) {
  14234. this.onDisposeObservable.remove(this._onDisposeObserver);
  14235. }
  14236. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  14237. },
  14238. enumerable: true,
  14239. configurable: true
  14240. });
  14241. Node.prototype.getScene = function () {
  14242. return this._scene;
  14243. };
  14244. Node.prototype.getEngine = function () {
  14245. return this._scene.getEngine();
  14246. };
  14247. Node.prototype.addBehavior = function (behavior) {
  14248. var _this = this;
  14249. var index = this._behaviors.indexOf(behavior);
  14250. if (index !== -1) {
  14251. return this;
  14252. }
  14253. behavior.init();
  14254. if (this._scene.isLoading) {
  14255. // We defer the attach when the scene will be loaded
  14256. var observer = this._scene.onDataLoadedObservable.add(function () {
  14257. behavior.attach(_this);
  14258. setTimeout(function () {
  14259. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  14260. _this._scene.onDataLoadedObservable.remove(observer);
  14261. }, 0);
  14262. });
  14263. }
  14264. else {
  14265. behavior.attach(this);
  14266. }
  14267. this._behaviors.push(behavior);
  14268. return this;
  14269. };
  14270. Node.prototype.removeBehavior = function (behavior) {
  14271. var index = this._behaviors.indexOf(behavior);
  14272. if (index === -1) {
  14273. return this;
  14274. }
  14275. this._behaviors[index].detach();
  14276. this._behaviors.splice(index, 1);
  14277. return this;
  14278. };
  14279. Object.defineProperty(Node.prototype, "behaviors", {
  14280. get: function () {
  14281. return this._behaviors;
  14282. },
  14283. enumerable: true,
  14284. configurable: true
  14285. });
  14286. Node.prototype.getBehaviorByName = function (name) {
  14287. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  14288. var behavior = _a[_i];
  14289. if (behavior.name === name) {
  14290. return behavior;
  14291. }
  14292. }
  14293. return null;
  14294. };
  14295. // override it in derived class
  14296. Node.prototype.getWorldMatrix = function () {
  14297. return BABYLON.Matrix.Identity();
  14298. };
  14299. // override it in derived class if you add new variables to the cache
  14300. // and call the parent class method
  14301. Node.prototype._initCache = function () {
  14302. this._cache = {};
  14303. this._cache.parent = undefined;
  14304. };
  14305. Node.prototype.updateCache = function (force) {
  14306. if (!force && this.isSynchronized())
  14307. return;
  14308. this._cache.parent = this.parent;
  14309. this._updateCache();
  14310. };
  14311. // override it in derived class if you add new variables to the cache
  14312. // and call the parent class method if !ignoreParentClass
  14313. Node.prototype._updateCache = function (ignoreParentClass) {
  14314. };
  14315. // override it in derived class if you add new variables to the cache
  14316. Node.prototype._isSynchronized = function () {
  14317. return true;
  14318. };
  14319. Node.prototype._markSyncedWithParent = function () {
  14320. if (this.parent) {
  14321. this._parentRenderId = this.parent._currentRenderId;
  14322. }
  14323. };
  14324. Node.prototype.isSynchronizedWithParent = function () {
  14325. if (!this.parent) {
  14326. return true;
  14327. }
  14328. if (this._parentRenderId !== this.parent._currentRenderId) {
  14329. return false;
  14330. }
  14331. return this.parent.isSynchronized();
  14332. };
  14333. Node.prototype.isSynchronized = function (updateCache) {
  14334. var check = this.hasNewParent();
  14335. check = check || !this.isSynchronizedWithParent();
  14336. check = check || !this._isSynchronized();
  14337. if (updateCache)
  14338. this.updateCache(true);
  14339. return !check;
  14340. };
  14341. Node.prototype.hasNewParent = function (update) {
  14342. if (this._cache.parent === this.parent)
  14343. return false;
  14344. if (update)
  14345. this._cache.parent = this.parent;
  14346. return true;
  14347. };
  14348. /**
  14349. * Is this node ready to be used/rendered
  14350. * @return {boolean} is it ready
  14351. */
  14352. Node.prototype.isReady = function () {
  14353. return this._isReady;
  14354. };
  14355. /**
  14356. * Is this node enabled.
  14357. * If the node has a parent, all ancestors will be checked and false will be returned if any are false (not enabled), otherwise will return true.
  14358. * @param {boolean} [checkAncestors=true] - Indicates if this method should check the ancestors. The default is to check the ancestors. If set to false, the method will return the value of this node without checking ancestors.
  14359. * @return {boolean} whether this node (and its parent) is enabled.
  14360. * @see setEnabled
  14361. */
  14362. Node.prototype.isEnabled = function (checkAncestors) {
  14363. if (checkAncestors === void 0) { checkAncestors = true; }
  14364. if (checkAncestors === false) {
  14365. return this._isEnabled;
  14366. }
  14367. if (this._isEnabled === false) {
  14368. return false;
  14369. }
  14370. if (this.parent !== undefined && this.parent !== null) {
  14371. return this.parent.isEnabled(checkAncestors);
  14372. }
  14373. return true;
  14374. };
  14375. /**
  14376. * Set the enabled state of this node.
  14377. * @param {boolean} value - the new enabled state
  14378. * @see isEnabled
  14379. */
  14380. Node.prototype.setEnabled = function (value) {
  14381. this._isEnabled = value;
  14382. };
  14383. /**
  14384. * Is this node a descendant of the given node.
  14385. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  14386. * @param {BABYLON.Node} ancestor - The parent node to inspect
  14387. * @see parent
  14388. */
  14389. Node.prototype.isDescendantOf = function (ancestor) {
  14390. if (this.parent) {
  14391. if (this.parent === ancestor) {
  14392. return true;
  14393. }
  14394. return this.parent.isDescendantOf(ancestor);
  14395. }
  14396. return false;
  14397. };
  14398. /**
  14399. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  14400. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  14401. * @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.
  14402. * @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.
  14403. */
  14404. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  14405. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  14406. if (!this._children) {
  14407. return;
  14408. }
  14409. for (var index = 0; index < this._children.length; index++) {
  14410. var item = this._children[index];
  14411. if (!predicate || predicate(item)) {
  14412. results.push(item);
  14413. }
  14414. if (!directDescendantsOnly) {
  14415. item._getDescendants(results, false, predicate);
  14416. }
  14417. }
  14418. };
  14419. /**
  14420. * Will return all nodes that have this node as ascendant.
  14421. * @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.
  14422. * @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.
  14423. * @return {BABYLON.Node[]} all children nodes of all types.
  14424. */
  14425. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  14426. var results = new Array();
  14427. this._getDescendants(results, directDescendantsOnly, predicate);
  14428. return results;
  14429. };
  14430. /**
  14431. * Get all child-meshes of this node.
  14432. */
  14433. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  14434. var results = [];
  14435. this._getDescendants(results, directDescendantsOnly, function (node) {
  14436. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  14437. });
  14438. return results;
  14439. };
  14440. /**
  14441. * Get all child-transformNodes of this node.
  14442. */
  14443. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  14444. var results = [];
  14445. this._getDescendants(results, directDescendantsOnly, function (node) {
  14446. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  14447. });
  14448. return results;
  14449. };
  14450. /**
  14451. * Get all direct children of this node.
  14452. */
  14453. Node.prototype.getChildren = function (predicate) {
  14454. return this.getDescendants(true, predicate);
  14455. };
  14456. Node.prototype._setReady = function (state) {
  14457. if (state === this._isReady) {
  14458. return;
  14459. }
  14460. if (!state) {
  14461. this._isReady = false;
  14462. return;
  14463. }
  14464. this._isReady = true;
  14465. if (this.onReady) {
  14466. this.onReady(this);
  14467. }
  14468. };
  14469. Node.prototype.getAnimationByName = function (name) {
  14470. for (var i = 0; i < this.animations.length; i++) {
  14471. var animation = this.animations[i];
  14472. if (animation.name === name) {
  14473. return animation;
  14474. }
  14475. }
  14476. return null;
  14477. };
  14478. Node.prototype.createAnimationRange = function (name, from, to) {
  14479. // check name not already in use
  14480. if (!this._ranges[name]) {
  14481. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  14482. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  14483. if (this.animations[i]) {
  14484. this.animations[i].createRange(name, from, to);
  14485. }
  14486. }
  14487. }
  14488. };
  14489. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  14490. if (deleteFrames === void 0) { deleteFrames = true; }
  14491. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  14492. if (this.animations[i]) {
  14493. this.animations[i].deleteRange(name, deleteFrames);
  14494. }
  14495. }
  14496. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  14497. };
  14498. Node.prototype.getAnimationRange = function (name) {
  14499. return this._ranges[name];
  14500. };
  14501. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  14502. var range = this.getAnimationRange(name);
  14503. if (!range) {
  14504. return;
  14505. }
  14506. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  14507. };
  14508. Node.prototype.serializeAnimationRanges = function () {
  14509. var serializationRanges = [];
  14510. for (var name in this._ranges) {
  14511. var localRange = this._ranges[name];
  14512. if (!localRange) {
  14513. continue;
  14514. }
  14515. var range = {};
  14516. range.name = name;
  14517. range.from = localRange.from;
  14518. range.to = localRange.to;
  14519. serializationRanges.push(range);
  14520. }
  14521. return serializationRanges;
  14522. };
  14523. // override it in derived class
  14524. Node.prototype.computeWorldMatrix = function (force) {
  14525. return BABYLON.Matrix.Identity();
  14526. };
  14527. Node.prototype.dispose = function () {
  14528. this.parent = null;
  14529. // Callback
  14530. this.onDisposeObservable.notifyObservers(this);
  14531. this.onDisposeObservable.clear();
  14532. // Behaviors
  14533. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  14534. var behavior = _a[_i];
  14535. behavior.detach();
  14536. }
  14537. this._behaviors = [];
  14538. };
  14539. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  14540. if (parsedNode.ranges) {
  14541. for (var index = 0; index < parsedNode.ranges.length; index++) {
  14542. var data = parsedNode.ranges[index];
  14543. node.createAnimationRange(data.name, data.from, data.to);
  14544. }
  14545. }
  14546. };
  14547. __decorate([
  14548. BABYLON.serialize()
  14549. ], Node.prototype, "name", void 0);
  14550. __decorate([
  14551. BABYLON.serialize()
  14552. ], Node.prototype, "id", void 0);
  14553. __decorate([
  14554. BABYLON.serialize()
  14555. ], Node.prototype, "uniqueId", void 0);
  14556. __decorate([
  14557. BABYLON.serialize()
  14558. ], Node.prototype, "state", void 0);
  14559. __decorate([
  14560. BABYLON.serialize()
  14561. ], Node.prototype, "metadata", void 0);
  14562. return Node;
  14563. }());
  14564. BABYLON.Node = Node;
  14565. })(BABYLON || (BABYLON = {}));
  14566. //# sourceMappingURL=babylon.node.js.map
  14567. var BABYLON;
  14568. (function (BABYLON) {
  14569. var BoundingSphere = /** @class */ (function () {
  14570. function BoundingSphere(minimum, maximum) {
  14571. this.minimum = minimum;
  14572. this.maximum = maximum;
  14573. this._tempRadiusVector = BABYLON.Vector3.Zero();
  14574. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  14575. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  14576. this.radius = distance * 0.5;
  14577. this.centerWorld = BABYLON.Vector3.Zero();
  14578. this._update(BABYLON.Matrix.Identity());
  14579. }
  14580. // Methods
  14581. BoundingSphere.prototype._update = function (world) {
  14582. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  14583. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  14584. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  14585. };
  14586. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  14587. for (var i = 0; i < 6; i++) {
  14588. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  14589. return false;
  14590. }
  14591. return true;
  14592. };
  14593. BoundingSphere.prototype.intersectsPoint = function (point) {
  14594. var x = this.centerWorld.x - point.x;
  14595. var y = this.centerWorld.y - point.y;
  14596. var z = this.centerWorld.z - point.z;
  14597. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  14598. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  14599. return false;
  14600. return true;
  14601. };
  14602. // Statics
  14603. BoundingSphere.Intersects = function (sphere0, sphere1) {
  14604. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  14605. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  14606. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  14607. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  14608. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  14609. return false;
  14610. return true;
  14611. };
  14612. return BoundingSphere;
  14613. }());
  14614. BABYLON.BoundingSphere = BoundingSphere;
  14615. })(BABYLON || (BABYLON = {}));
  14616. //# sourceMappingURL=babylon.boundingSphere.js.map
  14617. var BABYLON;
  14618. (function (BABYLON) {
  14619. var BoundingBox = /** @class */ (function () {
  14620. function BoundingBox(minimum, maximum) {
  14621. this.minimum = minimum;
  14622. this.maximum = maximum;
  14623. this.vectors = new Array();
  14624. this.vectorsWorld = new Array();
  14625. // Bounding vectors
  14626. this.vectors.push(this.minimum.clone());
  14627. this.vectors.push(this.maximum.clone());
  14628. this.vectors.push(this.minimum.clone());
  14629. this.vectors[2].x = this.maximum.x;
  14630. this.vectors.push(this.minimum.clone());
  14631. this.vectors[3].y = this.maximum.y;
  14632. this.vectors.push(this.minimum.clone());
  14633. this.vectors[4].z = this.maximum.z;
  14634. this.vectors.push(this.maximum.clone());
  14635. this.vectors[5].z = this.minimum.z;
  14636. this.vectors.push(this.maximum.clone());
  14637. this.vectors[6].x = this.minimum.x;
  14638. this.vectors.push(this.maximum.clone());
  14639. this.vectors[7].y = this.minimum.y;
  14640. // OBB
  14641. this.center = this.maximum.add(this.minimum).scale(0.5);
  14642. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  14643. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  14644. // World
  14645. for (var index = 0; index < this.vectors.length; index++) {
  14646. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  14647. }
  14648. this.minimumWorld = BABYLON.Vector3.Zero();
  14649. this.maximumWorld = BABYLON.Vector3.Zero();
  14650. this.centerWorld = BABYLON.Vector3.Zero();
  14651. this.extendSizeWorld = BABYLON.Vector3.Zero();
  14652. this._update(BABYLON.Matrix.Identity());
  14653. }
  14654. // Methods
  14655. BoundingBox.prototype.getWorldMatrix = function () {
  14656. return this._worldMatrix;
  14657. };
  14658. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  14659. this._worldMatrix.copyFrom(matrix);
  14660. return this;
  14661. };
  14662. BoundingBox.prototype._update = function (world) {
  14663. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  14664. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  14665. for (var index = 0; index < this.vectors.length; index++) {
  14666. var v = this.vectorsWorld[index];
  14667. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  14668. if (v.x < this.minimumWorld.x)
  14669. this.minimumWorld.x = v.x;
  14670. if (v.y < this.minimumWorld.y)
  14671. this.minimumWorld.y = v.y;
  14672. if (v.z < this.minimumWorld.z)
  14673. this.minimumWorld.z = v.z;
  14674. if (v.x > this.maximumWorld.x)
  14675. this.maximumWorld.x = v.x;
  14676. if (v.y > this.maximumWorld.y)
  14677. this.maximumWorld.y = v.y;
  14678. if (v.z > this.maximumWorld.z)
  14679. this.maximumWorld.z = v.z;
  14680. }
  14681. // Extend
  14682. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  14683. this.extendSizeWorld.scaleInPlace(0.5);
  14684. // OBB
  14685. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  14686. this.centerWorld.scaleInPlace(0.5);
  14687. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  14688. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  14689. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  14690. this._worldMatrix = world;
  14691. };
  14692. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  14693. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  14694. };
  14695. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14696. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  14697. };
  14698. BoundingBox.prototype.intersectsPoint = function (point) {
  14699. var delta = -BABYLON.Epsilon;
  14700. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  14701. return false;
  14702. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  14703. return false;
  14704. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  14705. return false;
  14706. return true;
  14707. };
  14708. BoundingBox.prototype.intersectsSphere = function (sphere) {
  14709. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  14710. };
  14711. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  14712. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  14713. return false;
  14714. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  14715. return false;
  14716. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  14717. return false;
  14718. return true;
  14719. };
  14720. // Statics
  14721. BoundingBox.Intersects = function (box0, box1) {
  14722. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  14723. return false;
  14724. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  14725. return false;
  14726. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  14727. return false;
  14728. return true;
  14729. };
  14730. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  14731. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  14732. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  14733. return (num <= (sphereRadius * sphereRadius));
  14734. };
  14735. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  14736. for (var p = 0; p < 6; p++) {
  14737. for (var i = 0; i < 8; i++) {
  14738. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  14739. return false;
  14740. }
  14741. }
  14742. }
  14743. return true;
  14744. };
  14745. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  14746. for (var p = 0; p < 6; p++) {
  14747. var inCount = 8;
  14748. for (var i = 0; i < 8; i++) {
  14749. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  14750. --inCount;
  14751. }
  14752. else {
  14753. break;
  14754. }
  14755. }
  14756. if (inCount === 0)
  14757. return false;
  14758. }
  14759. return true;
  14760. };
  14761. return BoundingBox;
  14762. }());
  14763. BABYLON.BoundingBox = BoundingBox;
  14764. })(BABYLON || (BABYLON = {}));
  14765. //# sourceMappingURL=babylon.boundingBox.js.map
  14766. var BABYLON;
  14767. (function (BABYLON) {
  14768. var computeBoxExtents = function (axis, box) {
  14769. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  14770. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  14771. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  14772. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  14773. var r = r0 + r1 + r2;
  14774. return {
  14775. min: p - r,
  14776. max: p + r
  14777. };
  14778. };
  14779. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  14780. var axisOverlap = function (axis, box0, box1) {
  14781. var result0 = computeBoxExtents(axis, box0);
  14782. var result1 = computeBoxExtents(axis, box1);
  14783. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  14784. };
  14785. var BoundingInfo = /** @class */ (function () {
  14786. function BoundingInfo(minimum, maximum) {
  14787. this.minimum = minimum;
  14788. this.maximum = maximum;
  14789. this._isLocked = false;
  14790. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  14791. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  14792. }
  14793. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  14794. get: function () {
  14795. return this._isLocked;
  14796. },
  14797. set: function (value) {
  14798. this._isLocked = value;
  14799. },
  14800. enumerable: true,
  14801. configurable: true
  14802. });
  14803. // Methods
  14804. BoundingInfo.prototype.update = function (world) {
  14805. if (this._isLocked) {
  14806. return;
  14807. }
  14808. this.boundingBox._update(world);
  14809. this.boundingSphere._update(world);
  14810. };
  14811. /**
  14812. * Recreate the bounding info to be centered around a specific point given a specific extend.
  14813. * @param center New center of the bounding info
  14814. * @param extend New extend of the bounding info
  14815. */
  14816. BoundingInfo.prototype.centerOn = function (center, extend) {
  14817. this.minimum = center.subtract(extend);
  14818. this.maximum = center.add(extend);
  14819. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  14820. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  14821. return this;
  14822. };
  14823. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  14824. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  14825. return false;
  14826. return this.boundingBox.isInFrustum(frustumPlanes);
  14827. };
  14828. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  14829. /**
  14830. * Gets the world distance between the min and max points of the bounding box
  14831. */
  14832. get: function () {
  14833. var boundingBox = this.boundingBox;
  14834. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  14835. return size.length();
  14836. },
  14837. enumerable: true,
  14838. configurable: true
  14839. });
  14840. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14841. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  14842. };
  14843. BoundingInfo.prototype._checkCollision = function (collider) {
  14844. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  14845. };
  14846. BoundingInfo.prototype.intersectsPoint = function (point) {
  14847. if (!this.boundingSphere.centerWorld) {
  14848. return false;
  14849. }
  14850. if (!this.boundingSphere.intersectsPoint(point)) {
  14851. return false;
  14852. }
  14853. if (!this.boundingBox.intersectsPoint(point)) {
  14854. return false;
  14855. }
  14856. return true;
  14857. };
  14858. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  14859. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  14860. return false;
  14861. }
  14862. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  14863. return false;
  14864. }
  14865. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  14866. return false;
  14867. }
  14868. if (!precise) {
  14869. return true;
  14870. }
  14871. var box0 = this.boundingBox;
  14872. var box1 = boundingInfo.boundingBox;
  14873. if (!axisOverlap(box0.directions[0], box0, box1))
  14874. return false;
  14875. if (!axisOverlap(box0.directions[1], box0, box1))
  14876. return false;
  14877. if (!axisOverlap(box0.directions[2], box0, box1))
  14878. return false;
  14879. if (!axisOverlap(box1.directions[0], box0, box1))
  14880. return false;
  14881. if (!axisOverlap(box1.directions[1], box0, box1))
  14882. return false;
  14883. if (!axisOverlap(box1.directions[2], box0, box1))
  14884. return false;
  14885. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  14886. return false;
  14887. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  14888. return false;
  14889. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  14890. return false;
  14891. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  14892. return false;
  14893. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  14894. return false;
  14895. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  14896. return false;
  14897. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  14898. return false;
  14899. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  14900. return false;
  14901. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  14902. return false;
  14903. return true;
  14904. };
  14905. return BoundingInfo;
  14906. }());
  14907. BABYLON.BoundingInfo = BoundingInfo;
  14908. })(BABYLON || (BABYLON = {}));
  14909. //# sourceMappingURL=babylon.boundingInfo.js.map
  14910. var BABYLON;
  14911. (function (BABYLON) {
  14912. var TransformNode = /** @class */ (function (_super) {
  14913. __extends(TransformNode, _super);
  14914. function TransformNode(name, scene, isPure) {
  14915. if (scene === void 0) { scene = null; }
  14916. if (isPure === void 0) { isPure = true; }
  14917. var _this = _super.call(this, name, scene) || this;
  14918. // Properties
  14919. _this._rotation = BABYLON.Vector3.Zero();
  14920. _this._scaling = BABYLON.Vector3.One();
  14921. _this._isDirty = false;
  14922. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  14923. _this.scalingDeterminant = 1;
  14924. _this.infiniteDistance = false;
  14925. _this.position = BABYLON.Vector3.Zero();
  14926. _this._localWorld = BABYLON.Matrix.Zero();
  14927. _this._worldMatrix = BABYLON.Matrix.Zero();
  14928. _this._worldMatrixDeterminant = 0;
  14929. _this._absolutePosition = BABYLON.Vector3.Zero();
  14930. _this._pivotMatrix = BABYLON.Matrix.Identity();
  14931. _this._postMultiplyPivotMatrix = false;
  14932. _this._isWorldMatrixFrozen = false;
  14933. /**
  14934. * An event triggered after the world matrix is updated
  14935. * @type {BABYLON.Observable}
  14936. */
  14937. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  14938. _this._nonUniformScaling = false;
  14939. if (isPure) {
  14940. _this.getScene().addTransformNode(_this);
  14941. }
  14942. return _this;
  14943. }
  14944. Object.defineProperty(TransformNode.prototype, "rotation", {
  14945. /**
  14946. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  14947. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  14948. * Default : (0.0, 0.0, 0.0)
  14949. */
  14950. get: function () {
  14951. return this._rotation;
  14952. },
  14953. set: function (newRotation) {
  14954. this._rotation = newRotation;
  14955. },
  14956. enumerable: true,
  14957. configurable: true
  14958. });
  14959. Object.defineProperty(TransformNode.prototype, "scaling", {
  14960. /**
  14961. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14962. * Default : (1.0, 1.0, 1.0)
  14963. */
  14964. get: function () {
  14965. return this._scaling;
  14966. },
  14967. /**
  14968. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14969. * Default : (1.0, 1.0, 1.0)
  14970. */
  14971. set: function (newScaling) {
  14972. this._scaling = newScaling;
  14973. },
  14974. enumerable: true,
  14975. configurable: true
  14976. });
  14977. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  14978. /**
  14979. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  14980. * It's null by default.
  14981. * 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)
  14982. */
  14983. get: function () {
  14984. return this._rotationQuaternion;
  14985. },
  14986. set: function (quaternion) {
  14987. this._rotationQuaternion = quaternion;
  14988. //reset the rotation vector.
  14989. if (quaternion && this.rotation.length()) {
  14990. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  14991. }
  14992. },
  14993. enumerable: true,
  14994. configurable: true
  14995. });
  14996. /**
  14997. * Returns the latest update of the World matrix
  14998. * Returns a Matrix.
  14999. */
  15000. TransformNode.prototype.getWorldMatrix = function () {
  15001. if (this._currentRenderId !== this.getScene().getRenderId()) {
  15002. this.computeWorldMatrix();
  15003. }
  15004. return this._worldMatrix;
  15005. };
  15006. /**
  15007. * Returns the latest update of the World matrix determinant.
  15008. */
  15009. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  15010. return this._worldMatrixDeterminant;
  15011. };
  15012. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  15013. /**
  15014. * Returns directly the latest state of the mesh World matrix.
  15015. * A Matrix is returned.
  15016. */
  15017. get: function () {
  15018. return this._worldMatrix;
  15019. },
  15020. enumerable: true,
  15021. configurable: true
  15022. });
  15023. /**
  15024. * Copies the paramater passed Matrix into the mesh Pose matrix.
  15025. * Returns the AbstractMesh.
  15026. */
  15027. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  15028. this._poseMatrix.copyFrom(matrix);
  15029. return this;
  15030. };
  15031. /**
  15032. * Returns the mesh Pose matrix.
  15033. * Returned object : Matrix
  15034. */
  15035. TransformNode.prototype.getPoseMatrix = function () {
  15036. return this._poseMatrix;
  15037. };
  15038. TransformNode.prototype._isSynchronized = function () {
  15039. if (this._isDirty) {
  15040. return false;
  15041. }
  15042. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  15043. return false;
  15044. if (this._cache.pivotMatrixUpdated) {
  15045. return false;
  15046. }
  15047. if (this.infiniteDistance) {
  15048. return false;
  15049. }
  15050. if (!this._cache.position.equals(this.position))
  15051. return false;
  15052. if (this.rotationQuaternion) {
  15053. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  15054. return false;
  15055. }
  15056. if (!this._cache.rotation.equals(this.rotation))
  15057. return false;
  15058. if (!this._cache.scaling.equals(this.scaling))
  15059. return false;
  15060. return true;
  15061. };
  15062. TransformNode.prototype._initCache = function () {
  15063. _super.prototype._initCache.call(this);
  15064. this._cache.localMatrixUpdated = false;
  15065. this._cache.position = BABYLON.Vector3.Zero();
  15066. this._cache.scaling = BABYLON.Vector3.Zero();
  15067. this._cache.rotation = BABYLON.Vector3.Zero();
  15068. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  15069. this._cache.billboardMode = -1;
  15070. };
  15071. TransformNode.prototype.markAsDirty = function (property) {
  15072. if (property === "rotation") {
  15073. this.rotationQuaternion = null;
  15074. }
  15075. this._currentRenderId = Number.MAX_VALUE;
  15076. this._isDirty = true;
  15077. return this;
  15078. };
  15079. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  15080. /**
  15081. * Returns the current mesh absolute position.
  15082. * Retuns a Vector3.
  15083. */
  15084. get: function () {
  15085. return this._absolutePosition;
  15086. },
  15087. enumerable: true,
  15088. configurable: true
  15089. });
  15090. /**
  15091. * Sets a new pivot matrix to the mesh.
  15092. * Returns the AbstractMesh.
  15093. */
  15094. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  15095. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = false; }
  15096. this._pivotMatrix = matrix.clone();
  15097. this._cache.pivotMatrixUpdated = true;
  15098. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  15099. if (this._postMultiplyPivotMatrix) {
  15100. this._pivotMatrixInverse = BABYLON.Matrix.Invert(matrix);
  15101. }
  15102. return this;
  15103. };
  15104. /**
  15105. * Returns the mesh pivot matrix.
  15106. * Default : Identity.
  15107. * A Matrix is returned.
  15108. */
  15109. TransformNode.prototype.getPivotMatrix = function () {
  15110. return this._pivotMatrix;
  15111. };
  15112. /**
  15113. * Prevents the World matrix to be computed any longer.
  15114. * Returns the AbstractMesh.
  15115. */
  15116. TransformNode.prototype.freezeWorldMatrix = function () {
  15117. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  15118. this.computeWorldMatrix(true);
  15119. this._isWorldMatrixFrozen = true;
  15120. return this;
  15121. };
  15122. /**
  15123. * Allows back the World matrix computation.
  15124. * Returns the AbstractMesh.
  15125. */
  15126. TransformNode.prototype.unfreezeWorldMatrix = function () {
  15127. this._isWorldMatrixFrozen = false;
  15128. this.computeWorldMatrix(true);
  15129. return this;
  15130. };
  15131. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  15132. /**
  15133. * True if the World matrix has been frozen.
  15134. * Returns a boolean.
  15135. */
  15136. get: function () {
  15137. return this._isWorldMatrixFrozen;
  15138. },
  15139. enumerable: true,
  15140. configurable: true
  15141. });
  15142. /**
  15143. * Retuns the mesh absolute position in the World.
  15144. * Returns a Vector3.
  15145. */
  15146. TransformNode.prototype.getAbsolutePosition = function () {
  15147. this.computeWorldMatrix();
  15148. return this._absolutePosition;
  15149. };
  15150. /**
  15151. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  15152. * Returns the AbstractMesh.
  15153. */
  15154. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  15155. if (!absolutePosition) {
  15156. return this;
  15157. }
  15158. var absolutePositionX;
  15159. var absolutePositionY;
  15160. var absolutePositionZ;
  15161. if (absolutePosition.x === undefined) {
  15162. if (arguments.length < 3) {
  15163. return this;
  15164. }
  15165. absolutePositionX = arguments[0];
  15166. absolutePositionY = arguments[1];
  15167. absolutePositionZ = arguments[2];
  15168. }
  15169. else {
  15170. absolutePositionX = absolutePosition.x;
  15171. absolutePositionY = absolutePosition.y;
  15172. absolutePositionZ = absolutePosition.z;
  15173. }
  15174. if (this.parent) {
  15175. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  15176. invertParentWorldMatrix.invert();
  15177. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  15178. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  15179. }
  15180. else {
  15181. this.position.x = absolutePositionX;
  15182. this.position.y = absolutePositionY;
  15183. this.position.z = absolutePositionZ;
  15184. }
  15185. return this;
  15186. };
  15187. /**
  15188. * Sets the mesh position in its local space.
  15189. * Returns the AbstractMesh.
  15190. */
  15191. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  15192. this.computeWorldMatrix();
  15193. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  15194. return this;
  15195. };
  15196. /**
  15197. * Returns the mesh position in the local space from the current World matrix values.
  15198. * Returns a new Vector3.
  15199. */
  15200. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  15201. this.computeWorldMatrix();
  15202. var invLocalWorldMatrix = this._localWorld.clone();
  15203. invLocalWorldMatrix.invert();
  15204. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  15205. };
  15206. /**
  15207. * Translates the mesh along the passed Vector3 in its local space.
  15208. * Returns the AbstractMesh.
  15209. */
  15210. TransformNode.prototype.locallyTranslate = function (vector3) {
  15211. this.computeWorldMatrix(true);
  15212. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  15213. return this;
  15214. };
  15215. /**
  15216. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  15217. * @param targetPoint the position (must be in same space as current mesh) to look at
  15218. * @param yawCor optional yaw (y-axis) correction in radians
  15219. * @param pitchCor optional pitch (x-axis) correction in radians
  15220. * @param rollCor optional roll (z-axis) correction in radians
  15221. * @param space the choosen space of the target
  15222. * @returns the TransformNode.
  15223. */
  15224. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  15225. if (yawCor === void 0) { yawCor = 0; }
  15226. if (pitchCor === void 0) { pitchCor = 0; }
  15227. if (rollCor === void 0) { rollCor = 0; }
  15228. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  15229. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  15230. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  15231. targetPoint.subtractToRef(pos, dv);
  15232. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  15233. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  15234. var pitch = Math.atan2(dv.y, len);
  15235. if (this.rotationQuaternion) {
  15236. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  15237. }
  15238. else {
  15239. this.rotation.x = pitch + pitchCor;
  15240. this.rotation.y = yaw + yawCor;
  15241. this.rotation.z = rollCor;
  15242. }
  15243. return this;
  15244. };
  15245. /**
  15246. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  15247. * This Vector3 is expressed in the World space.
  15248. */
  15249. TransformNode.prototype.getDirection = function (localAxis) {
  15250. var result = BABYLON.Vector3.Zero();
  15251. this.getDirectionToRef(localAxis, result);
  15252. return result;
  15253. };
  15254. /**
  15255. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  15256. * localAxis is expressed in the mesh local space.
  15257. * result is computed in the Wordl space from the mesh World matrix.
  15258. * Returns the AbstractMesh.
  15259. */
  15260. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  15261. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  15262. return this;
  15263. };
  15264. TransformNode.prototype.setPivotPoint = function (point, space) {
  15265. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  15266. if (this.getScene().getRenderId() == 0) {
  15267. this.computeWorldMatrix(true);
  15268. }
  15269. var wm = this.getWorldMatrix();
  15270. if (space == BABYLON.Space.WORLD) {
  15271. var tmat = BABYLON.Tmp.Matrix[0];
  15272. wm.invertToRef(tmat);
  15273. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  15274. }
  15275. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  15276. this._pivotMatrix.m[12] = -point.x;
  15277. this._pivotMatrix.m[13] = -point.y;
  15278. this._pivotMatrix.m[14] = -point.z;
  15279. this._cache.pivotMatrixUpdated = true;
  15280. return this;
  15281. };
  15282. /**
  15283. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  15284. */
  15285. TransformNode.prototype.getPivotPoint = function () {
  15286. var point = BABYLON.Vector3.Zero();
  15287. this.getPivotPointToRef(point);
  15288. return point;
  15289. };
  15290. /**
  15291. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  15292. * Returns the AbstractMesh.
  15293. */
  15294. TransformNode.prototype.getPivotPointToRef = function (result) {
  15295. result.x = -this._pivotMatrix.m[12];
  15296. result.y = -this._pivotMatrix.m[13];
  15297. result.z = -this._pivotMatrix.m[14];
  15298. return this;
  15299. };
  15300. /**
  15301. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  15302. */
  15303. TransformNode.prototype.getAbsolutePivotPoint = function () {
  15304. var point = BABYLON.Vector3.Zero();
  15305. this.getAbsolutePivotPointToRef(point);
  15306. return point;
  15307. };
  15308. /**
  15309. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  15310. * Returns the AbstractMesh.
  15311. */
  15312. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  15313. result.x = this._pivotMatrix.m[12];
  15314. result.y = this._pivotMatrix.m[13];
  15315. result.z = this._pivotMatrix.m[14];
  15316. this.getPivotPointToRef(result);
  15317. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  15318. return this;
  15319. };
  15320. /**
  15321. * Defines the passed node as the parent of the current node.
  15322. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  15323. * Returns the TransformNode.
  15324. */
  15325. TransformNode.prototype.setParent = function (node) {
  15326. if (node === null) {
  15327. var rotation = BABYLON.Tmp.Quaternion[0];
  15328. var position = BABYLON.Tmp.Vector3[0];
  15329. var scale = BABYLON.Tmp.Vector3[1];
  15330. if (this.parent && this.parent.computeWorldMatrix) {
  15331. this.parent.computeWorldMatrix(true);
  15332. }
  15333. this.computeWorldMatrix(true);
  15334. this.getWorldMatrix().decompose(scale, rotation, position);
  15335. if (this.rotationQuaternion) {
  15336. this.rotationQuaternion.copyFrom(rotation);
  15337. }
  15338. else {
  15339. rotation.toEulerAnglesToRef(this.rotation);
  15340. }
  15341. this.scaling.x = scale.x;
  15342. this.scaling.y = scale.y;
  15343. this.scaling.z = scale.z;
  15344. this.position.x = position.x;
  15345. this.position.y = position.y;
  15346. this.position.z = position.z;
  15347. }
  15348. else {
  15349. var rotation = BABYLON.Tmp.Quaternion[0];
  15350. var position = BABYLON.Tmp.Vector3[0];
  15351. var scale = BABYLON.Tmp.Vector3[1];
  15352. var diffMatrix = BABYLON.Tmp.Matrix[0];
  15353. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  15354. this.computeWorldMatrix(true);
  15355. node.computeWorldMatrix(true);
  15356. node.getWorldMatrix().invertToRef(invParentMatrix);
  15357. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  15358. diffMatrix.decompose(scale, rotation, position);
  15359. if (this.rotationQuaternion) {
  15360. this.rotationQuaternion.copyFrom(rotation);
  15361. }
  15362. else {
  15363. rotation.toEulerAnglesToRef(this.rotation);
  15364. }
  15365. this.position.x = position.x;
  15366. this.position.y = position.y;
  15367. this.position.z = position.z;
  15368. this.scaling.x = scale.x;
  15369. this.scaling.y = scale.y;
  15370. this.scaling.z = scale.z;
  15371. }
  15372. this.parent = node;
  15373. return this;
  15374. };
  15375. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  15376. get: function () {
  15377. return this._nonUniformScaling;
  15378. },
  15379. enumerable: true,
  15380. configurable: true
  15381. });
  15382. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  15383. if (this._nonUniformScaling === value) {
  15384. return false;
  15385. }
  15386. this._nonUniformScaling = true;
  15387. return true;
  15388. };
  15389. /**
  15390. * Attach the current TransformNode to another TransformNode associated with a bone
  15391. * @param bone Bone affecting the TransformNode
  15392. * @param affectedTransformNode TransformNode associated with the bone
  15393. */
  15394. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  15395. this._transformToBoneReferal = affectedTransformNode;
  15396. this.parent = bone;
  15397. if (bone.getWorldMatrix().determinant() < 0) {
  15398. this.scalingDeterminant *= -1;
  15399. }
  15400. return this;
  15401. };
  15402. TransformNode.prototype.detachFromBone = function () {
  15403. if (!this.parent) {
  15404. return this;
  15405. }
  15406. if (this.parent.getWorldMatrix().determinant() < 0) {
  15407. this.scalingDeterminant *= -1;
  15408. }
  15409. this._transformToBoneReferal = null;
  15410. this.parent = null;
  15411. return this;
  15412. };
  15413. /**
  15414. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  15415. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  15416. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  15417. * The passed axis is also normalized.
  15418. * Returns the AbstractMesh.
  15419. */
  15420. TransformNode.prototype.rotate = function (axis, amount, space) {
  15421. axis.normalize();
  15422. if (!this.rotationQuaternion) {
  15423. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  15424. this.rotation = BABYLON.Vector3.Zero();
  15425. }
  15426. var rotationQuaternion;
  15427. if (!space || space === BABYLON.Space.LOCAL) {
  15428. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  15429. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  15430. }
  15431. else {
  15432. if (this.parent) {
  15433. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  15434. invertParentWorldMatrix.invert();
  15435. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  15436. }
  15437. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  15438. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  15439. }
  15440. return this;
  15441. };
  15442. /**
  15443. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  15444. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  15445. * The passed axis is also normalized.
  15446. * Returns the AbstractMesh.
  15447. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  15448. */
  15449. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  15450. axis.normalize();
  15451. if (!this.rotationQuaternion) {
  15452. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  15453. this.rotation.copyFromFloats(0, 0, 0);
  15454. }
  15455. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  15456. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  15457. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  15458. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  15459. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  15460. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  15461. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  15462. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  15463. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  15464. return this;
  15465. };
  15466. /**
  15467. * Translates the mesh along the axis vector for the passed distance in the given space.
  15468. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  15469. * Returns the AbstractMesh.
  15470. */
  15471. TransformNode.prototype.translate = function (axis, distance, space) {
  15472. var displacementVector = axis.scale(distance);
  15473. if (!space || space === BABYLON.Space.LOCAL) {
  15474. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  15475. this.setPositionWithLocalVector(tempV3);
  15476. }
  15477. else {
  15478. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  15479. }
  15480. return this;
  15481. };
  15482. /**
  15483. * Adds a rotation step to the mesh current rotation.
  15484. * x, y, z are Euler angles expressed in radians.
  15485. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  15486. * This means this rotation is made in the mesh local space only.
  15487. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  15488. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  15489. * ```javascript
  15490. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  15491. * ```
  15492. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  15493. * 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.
  15494. * Returns the AbstractMesh.
  15495. */
  15496. TransformNode.prototype.addRotation = function (x, y, z) {
  15497. var rotationQuaternion;
  15498. if (this.rotationQuaternion) {
  15499. rotationQuaternion = this.rotationQuaternion;
  15500. }
  15501. else {
  15502. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  15503. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  15504. }
  15505. var accumulation = BABYLON.Tmp.Quaternion[0];
  15506. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  15507. rotationQuaternion.multiplyInPlace(accumulation);
  15508. if (!this.rotationQuaternion) {
  15509. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  15510. }
  15511. return this;
  15512. };
  15513. /**
  15514. * Computes the mesh World matrix and returns it.
  15515. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  15516. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  15517. * If the parameter `force`is set to `true`, the actual computation is done.
  15518. * Returns the mesh World Matrix.
  15519. */
  15520. TransformNode.prototype.computeWorldMatrix = function (force) {
  15521. if (this._isWorldMatrixFrozen) {
  15522. return this._worldMatrix;
  15523. }
  15524. if (!force && this.isSynchronized(true)) {
  15525. return this._worldMatrix;
  15526. }
  15527. this._cache.position.copyFrom(this.position);
  15528. this._cache.scaling.copyFrom(this.scaling);
  15529. this._cache.pivotMatrixUpdated = false;
  15530. this._cache.billboardMode = this.billboardMode;
  15531. this._currentRenderId = this.getScene().getRenderId();
  15532. this._isDirty = false;
  15533. // Scaling
  15534. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  15535. // Rotation
  15536. //rotate, if quaternion is set and rotation was used
  15537. if (this.rotationQuaternion) {
  15538. var len = this.rotation.length();
  15539. if (len) {
  15540. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  15541. this.rotation.copyFromFloats(0, 0, 0);
  15542. }
  15543. }
  15544. if (this.rotationQuaternion) {
  15545. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  15546. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  15547. }
  15548. else {
  15549. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  15550. this._cache.rotation.copyFrom(this.rotation);
  15551. }
  15552. // Translation
  15553. var camera = this.getScene().activeCamera;
  15554. if (this.infiniteDistance && !this.parent && camera) {
  15555. var cameraWorldMatrix = camera.getWorldMatrix();
  15556. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  15557. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  15558. }
  15559. else {
  15560. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  15561. }
  15562. // Composing transformations
  15563. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  15564. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  15565. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  15566. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  15567. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  15568. // Need to decompose each rotation here
  15569. var currentPosition = BABYLON.Tmp.Vector3[3];
  15570. if (this.parent && this.parent.getWorldMatrix) {
  15571. if (this._transformToBoneReferal) {
  15572. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15573. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  15574. }
  15575. else {
  15576. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  15577. }
  15578. }
  15579. else {
  15580. currentPosition.copyFrom(this.position);
  15581. }
  15582. currentPosition.subtractInPlace(camera.globalPosition);
  15583. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  15584. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  15585. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  15586. }
  15587. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  15588. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  15589. }
  15590. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  15591. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  15592. }
  15593. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  15594. }
  15595. else {
  15596. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  15597. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  15598. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  15599. }
  15600. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  15601. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  15602. }
  15603. // Local world
  15604. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  15605. // Parent
  15606. if (this.parent && this.parent.getWorldMatrix) {
  15607. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  15608. if (this._transformToBoneReferal) {
  15609. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15610. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  15611. }
  15612. else {
  15613. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  15614. }
  15615. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  15616. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  15617. this._worldMatrix.copyFrom(this._localWorld);
  15618. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  15619. }
  15620. else {
  15621. if (this._transformToBoneReferal) {
  15622. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15623. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  15624. }
  15625. else {
  15626. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  15627. }
  15628. }
  15629. this._markSyncedWithParent();
  15630. }
  15631. else {
  15632. this._worldMatrix.copyFrom(this._localWorld);
  15633. }
  15634. // Post multiply inverse of pivotMatrix
  15635. if (this._postMultiplyPivotMatrix) {
  15636. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  15637. }
  15638. // Normal matrix
  15639. if (this.scaling.isNonUniform) {
  15640. this._updateNonUniformScalingState(true);
  15641. }
  15642. else if (this.parent && this.parent._nonUniformScaling) {
  15643. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  15644. }
  15645. else {
  15646. this._updateNonUniformScalingState(false);
  15647. }
  15648. this._afterComputeWorldMatrix();
  15649. // Absolute position
  15650. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  15651. // Callbacks
  15652. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  15653. if (!this._poseMatrix) {
  15654. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  15655. }
  15656. // Cache the determinant
  15657. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  15658. return this._worldMatrix;
  15659. };
  15660. TransformNode.prototype._afterComputeWorldMatrix = function () {
  15661. };
  15662. /**
  15663. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  15664. * @param func: callback function to add
  15665. *
  15666. * Returns the TransformNode.
  15667. */
  15668. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  15669. this.onAfterWorldMatrixUpdateObservable.add(func);
  15670. return this;
  15671. };
  15672. /**
  15673. * Removes a registered callback function.
  15674. * Returns the TransformNode.
  15675. */
  15676. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  15677. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  15678. return this;
  15679. };
  15680. /**
  15681. * Clone the current transform node
  15682. * Returns the new transform node
  15683. * @param name Name of the new clone
  15684. * @param newParent New parent for the clone
  15685. * @param doNotCloneChildren Do not clone children hierarchy
  15686. */
  15687. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15688. var _this = this;
  15689. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  15690. result.name = name;
  15691. result.id = name;
  15692. if (newParent) {
  15693. result.parent = newParent;
  15694. }
  15695. if (!doNotCloneChildren) {
  15696. // Children
  15697. var directDescendants = this.getDescendants(true);
  15698. for (var index = 0; index < directDescendants.length; index++) {
  15699. var child = directDescendants[index];
  15700. if (child.clone) {
  15701. child.clone(name + "." + child.name, result);
  15702. }
  15703. }
  15704. }
  15705. return result;
  15706. };
  15707. TransformNode.prototype.serialize = function (currentSerializationObject) {
  15708. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  15709. serializationObject.type = this.getClassName();
  15710. // Parent
  15711. if (this.parent) {
  15712. serializationObject.parentId = this.parent.id;
  15713. }
  15714. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  15715. serializationObject.tags = BABYLON.Tags.GetTags(this);
  15716. }
  15717. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  15718. serializationObject.isEnabled = this.isEnabled();
  15719. // Parent
  15720. if (this.parent) {
  15721. serializationObject.parentId = this.parent.id;
  15722. }
  15723. return serializationObject;
  15724. };
  15725. // Statics
  15726. /**
  15727. * Returns a new TransformNode object parsed from the source provided.
  15728. * The parameter `parsedMesh` is the source.
  15729. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  15730. */
  15731. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  15732. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  15733. if (BABYLON.Tags) {
  15734. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  15735. }
  15736. if (parsedTransformNode.localMatrix) {
  15737. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  15738. }
  15739. else if (parsedTransformNode.pivotMatrix) {
  15740. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  15741. }
  15742. transformNode.setEnabled(parsedTransformNode.isEnabled);
  15743. // Parent
  15744. if (parsedTransformNode.parentId) {
  15745. transformNode._waitingParentId = parsedTransformNode.parentId;
  15746. }
  15747. return transformNode;
  15748. };
  15749. /**
  15750. * Disposes the TransformNode.
  15751. * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  15752. * Returns nothing.
  15753. */
  15754. TransformNode.prototype.dispose = function (doNotRecurse) {
  15755. // Animations
  15756. this.getScene().stopAnimation(this);
  15757. // Remove from scene
  15758. this.getScene().removeTransformNode(this);
  15759. if (!doNotRecurse) {
  15760. // Children
  15761. var objects = this.getDescendants(true);
  15762. for (var index = 0; index < objects.length; index++) {
  15763. objects[index].dispose();
  15764. }
  15765. }
  15766. else {
  15767. var childMeshes = this.getChildMeshes(true);
  15768. for (index = 0; index < childMeshes.length; index++) {
  15769. var child = childMeshes[index];
  15770. child.parent = null;
  15771. child.computeWorldMatrix(true);
  15772. }
  15773. }
  15774. this.onAfterWorldMatrixUpdateObservable.clear();
  15775. _super.prototype.dispose.call(this);
  15776. };
  15777. // Statics
  15778. TransformNode.BILLBOARDMODE_NONE = 0;
  15779. TransformNode.BILLBOARDMODE_X = 1;
  15780. TransformNode.BILLBOARDMODE_Y = 2;
  15781. TransformNode.BILLBOARDMODE_Z = 4;
  15782. TransformNode.BILLBOARDMODE_ALL = 7;
  15783. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  15784. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  15785. __decorate([
  15786. BABYLON.serializeAsVector3()
  15787. ], TransformNode.prototype, "_rotation", void 0);
  15788. __decorate([
  15789. BABYLON.serializeAsQuaternion()
  15790. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  15791. __decorate([
  15792. BABYLON.serializeAsVector3()
  15793. ], TransformNode.prototype, "_scaling", void 0);
  15794. __decorate([
  15795. BABYLON.serialize()
  15796. ], TransformNode.prototype, "billboardMode", void 0);
  15797. __decorate([
  15798. BABYLON.serialize()
  15799. ], TransformNode.prototype, "scalingDeterminant", void 0);
  15800. __decorate([
  15801. BABYLON.serialize()
  15802. ], TransformNode.prototype, "infiniteDistance", void 0);
  15803. __decorate([
  15804. BABYLON.serializeAsVector3()
  15805. ], TransformNode.prototype, "position", void 0);
  15806. return TransformNode;
  15807. }(BABYLON.Node));
  15808. BABYLON.TransformNode = TransformNode;
  15809. })(BABYLON || (BABYLON = {}));
  15810. //# sourceMappingURL=babylon.transformNode.js.map
  15811. var BABYLON;
  15812. (function (BABYLON) {
  15813. var AbstractMesh = /** @class */ (function (_super) {
  15814. __extends(AbstractMesh, _super);
  15815. // Constructor
  15816. function AbstractMesh(name, scene) {
  15817. if (scene === void 0) { scene = null; }
  15818. var _this = _super.call(this, name, scene, false) || this;
  15819. _this._facetNb = 0; // facet number
  15820. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  15821. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  15822. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  15823. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  15824. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  15825. _this._subDiv = {
  15826. max: 1,
  15827. X: 1,
  15828. Y: 1,
  15829. Z: 1
  15830. };
  15831. _this._facetDepthSort = false; // is the facet depth sort to be computed
  15832. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  15833. // Events
  15834. /**
  15835. * An event triggered when this mesh collides with another one
  15836. * @type {BABYLON.Observable}
  15837. */
  15838. _this.onCollideObservable = new BABYLON.Observable();
  15839. /**
  15840. * An event triggered when the collision's position changes
  15841. * @type {BABYLON.Observable}
  15842. */
  15843. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  15844. /**
  15845. * An event triggered when material is changed
  15846. * @type {BABYLON.Observable}
  15847. */
  15848. _this.onMaterialChangedObservable = new BABYLON.Observable();
  15849. // Properties
  15850. _this.definedFacingForward = true; // orientation for POV movement & rotation
  15851. /**
  15852. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  15853. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  15854. * or
  15855. * 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.
  15856. * for more info check WebGl documentations
  15857. */
  15858. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  15859. /**
  15860. * 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:
  15861. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  15862. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  15863. * 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.
  15864. */
  15865. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  15866. /**
  15867. * 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.
  15868. * The default value is -1 which means don't break the query and wait till the result.
  15869. */
  15870. _this.occlusionRetryCount = -1;
  15871. _this._occlusionInternalRetryCounter = 0;
  15872. _this._isOccluded = false;
  15873. _this._isOcclusionQueryInProgress = false;
  15874. _this._visibility = 1.0;
  15875. _this.alphaIndex = Number.MAX_VALUE;
  15876. _this.isVisible = true;
  15877. _this.isPickable = true;
  15878. _this.showBoundingBox = false;
  15879. _this.showSubMeshesBoundingBox = false;
  15880. _this.isBlocker = false;
  15881. _this.enablePointerMoveEvents = false;
  15882. _this.renderingGroupId = 0;
  15883. _this._receiveShadows = false;
  15884. _this.renderOutline = false;
  15885. _this.outlineColor = BABYLON.Color3.Red();
  15886. _this.outlineWidth = 0.02;
  15887. _this.renderOverlay = false;
  15888. _this.overlayColor = BABYLON.Color3.Red();
  15889. _this.overlayAlpha = 0.5;
  15890. _this._hasVertexAlpha = false;
  15891. _this._useVertexColors = true;
  15892. _this._computeBonesUsingShaders = true;
  15893. _this._numBoneInfluencers = 4;
  15894. _this._applyFog = true;
  15895. _this.useOctreeForRenderingSelection = true;
  15896. _this.useOctreeForPicking = true;
  15897. _this.useOctreeForCollisions = true;
  15898. _this._layerMask = 0x0FFFFFFF;
  15899. /**
  15900. * True if the mesh must be rendered in any case.
  15901. */
  15902. _this.alwaysSelectAsActiveMesh = false;
  15903. /**
  15904. * This scene's action manager
  15905. * @type {BABYLON.ActionManager}
  15906. */
  15907. _this.actionManager = null;
  15908. // Physics
  15909. _this.physicsImpostor = null;
  15910. // Collisions
  15911. _this._checkCollisions = false;
  15912. _this._collisionMask = -1;
  15913. _this._collisionGroup = -1;
  15914. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  15915. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  15916. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  15917. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  15918. // Edges
  15919. _this.edgesWidth = 1;
  15920. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  15921. // Cache
  15922. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  15923. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  15924. _this._isDisposed = false;
  15925. _this._renderId = 0;
  15926. _this._intersectionsInProgress = new Array();
  15927. _this._unIndexed = false;
  15928. _this._lightSources = new Array();
  15929. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  15930. if (collidedMesh === void 0) { collidedMesh = null; }
  15931. //TODO move this to the collision coordinator!
  15932. if (_this.getScene().workerCollisions)
  15933. newPosition.multiplyInPlace(_this._collider._radius);
  15934. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  15935. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  15936. _this.position.addInPlace(_this._diffPositionForCollisions);
  15937. }
  15938. if (collidedMesh) {
  15939. _this.onCollideObservable.notifyObservers(collidedMesh);
  15940. }
  15941. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  15942. };
  15943. _this.getScene().addMesh(_this);
  15944. _this._resyncLightSources();
  15945. return _this;
  15946. }
  15947. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  15948. get: function () {
  15949. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  15950. },
  15951. enumerable: true,
  15952. configurable: true
  15953. });
  15954. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  15955. get: function () {
  15956. return BABYLON.TransformNode.BILLBOARDMODE_X;
  15957. },
  15958. enumerable: true,
  15959. configurable: true
  15960. });
  15961. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  15962. get: function () {
  15963. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  15964. },
  15965. enumerable: true,
  15966. configurable: true
  15967. });
  15968. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  15969. get: function () {
  15970. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  15971. },
  15972. enumerable: true,
  15973. configurable: true
  15974. });
  15975. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  15976. get: function () {
  15977. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  15978. },
  15979. enumerable: true,
  15980. configurable: true
  15981. });
  15982. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  15983. /**
  15984. * Read-only : the number of facets in the mesh
  15985. */
  15986. get: function () {
  15987. return this._facetNb;
  15988. },
  15989. enumerable: true,
  15990. configurable: true
  15991. });
  15992. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  15993. /**
  15994. * The number (integer) of subdivisions per axis in the partioning space
  15995. */
  15996. get: function () {
  15997. return this._partitioningSubdivisions;
  15998. },
  15999. set: function (nb) {
  16000. this._partitioningSubdivisions = nb;
  16001. },
  16002. enumerable: true,
  16003. configurable: true
  16004. });
  16005. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  16006. /**
  16007. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  16008. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  16009. */
  16010. get: function () {
  16011. return this._partitioningBBoxRatio;
  16012. },
  16013. set: function (ratio) {
  16014. this._partitioningBBoxRatio = ratio;
  16015. },
  16016. enumerable: true,
  16017. configurable: true
  16018. });
  16019. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  16020. /**
  16021. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  16022. * Works only for updatable meshes.
  16023. * Doesn't work with multi-materials.
  16024. */
  16025. get: function () {
  16026. return this._facetDepthSort;
  16027. },
  16028. set: function (sort) {
  16029. this._facetDepthSort = sort;
  16030. },
  16031. enumerable: true,
  16032. configurable: true
  16033. });
  16034. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  16035. /**
  16036. * The location (Vector3) where the facet depth sort must be computed from.
  16037. * By default, the active camera position.
  16038. * Used only when facet depth sort is enabled.
  16039. */
  16040. get: function () {
  16041. return this._facetDepthSortFrom;
  16042. },
  16043. set: function (location) {
  16044. this._facetDepthSortFrom = location;
  16045. },
  16046. enumerable: true,
  16047. configurable: true
  16048. });
  16049. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  16050. /**
  16051. * Read-only boolean : is the feature facetData enabled ?
  16052. */
  16053. get: function () {
  16054. return this._facetDataEnabled;
  16055. },
  16056. enumerable: true,
  16057. configurable: true
  16058. });
  16059. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  16060. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  16061. return false;
  16062. }
  16063. this._markSubMeshesAsMiscDirty();
  16064. return true;
  16065. };
  16066. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  16067. set: function (callback) {
  16068. if (this._onCollideObserver) {
  16069. this.onCollideObservable.remove(this._onCollideObserver);
  16070. }
  16071. this._onCollideObserver = this.onCollideObservable.add(callback);
  16072. },
  16073. enumerable: true,
  16074. configurable: true
  16075. });
  16076. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  16077. set: function (callback) {
  16078. if (this._onCollisionPositionChangeObserver) {
  16079. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  16080. }
  16081. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  16082. },
  16083. enumerable: true,
  16084. configurable: true
  16085. });
  16086. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  16087. /**
  16088. * 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.
  16089. */
  16090. get: function () {
  16091. return this._isOccluded;
  16092. },
  16093. set: function (value) {
  16094. this._isOccluded = value;
  16095. },
  16096. enumerable: true,
  16097. configurable: true
  16098. });
  16099. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  16100. /**
  16101. * Flag to check the progress status of the query
  16102. */
  16103. get: function () {
  16104. return this._isOcclusionQueryInProgress;
  16105. },
  16106. enumerable: true,
  16107. configurable: true
  16108. });
  16109. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  16110. /**
  16111. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  16112. */
  16113. get: function () {
  16114. return this._visibility;
  16115. },
  16116. /**
  16117. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  16118. */
  16119. set: function (value) {
  16120. if (this._visibility === value) {
  16121. return;
  16122. }
  16123. this._visibility = value;
  16124. this._markSubMeshesAsMiscDirty();
  16125. },
  16126. enumerable: true,
  16127. configurable: true
  16128. });
  16129. Object.defineProperty(AbstractMesh.prototype, "material", {
  16130. get: function () {
  16131. return this._material;
  16132. },
  16133. set: function (value) {
  16134. if (this._material === value) {
  16135. return;
  16136. }
  16137. this._material = value;
  16138. if (this.onMaterialChangedObservable.hasObservers) {
  16139. this.onMaterialChangedObservable.notifyObservers(this);
  16140. }
  16141. if (!this.subMeshes) {
  16142. return;
  16143. }
  16144. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  16145. var subMesh = _a[_i];
  16146. subMesh.setEffect(null);
  16147. }
  16148. },
  16149. enumerable: true,
  16150. configurable: true
  16151. });
  16152. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  16153. get: function () {
  16154. return this._receiveShadows;
  16155. },
  16156. set: function (value) {
  16157. if (this._receiveShadows === value) {
  16158. return;
  16159. }
  16160. this._receiveShadows = value;
  16161. this._markSubMeshesAsLightDirty();
  16162. },
  16163. enumerable: true,
  16164. configurable: true
  16165. });
  16166. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  16167. get: function () {
  16168. return this._hasVertexAlpha;
  16169. },
  16170. set: function (value) {
  16171. if (this._hasVertexAlpha === value) {
  16172. return;
  16173. }
  16174. this._hasVertexAlpha = value;
  16175. this._markSubMeshesAsAttributesDirty();
  16176. this._markSubMeshesAsMiscDirty();
  16177. },
  16178. enumerable: true,
  16179. configurable: true
  16180. });
  16181. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  16182. get: function () {
  16183. return this._useVertexColors;
  16184. },
  16185. set: function (value) {
  16186. if (this._useVertexColors === value) {
  16187. return;
  16188. }
  16189. this._useVertexColors = value;
  16190. this._markSubMeshesAsAttributesDirty();
  16191. },
  16192. enumerable: true,
  16193. configurable: true
  16194. });
  16195. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  16196. get: function () {
  16197. return this._computeBonesUsingShaders;
  16198. },
  16199. set: function (value) {
  16200. if (this._computeBonesUsingShaders === value) {
  16201. return;
  16202. }
  16203. this._computeBonesUsingShaders = value;
  16204. this._markSubMeshesAsAttributesDirty();
  16205. },
  16206. enumerable: true,
  16207. configurable: true
  16208. });
  16209. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  16210. get: function () {
  16211. return this._numBoneInfluencers;
  16212. },
  16213. set: function (value) {
  16214. if (this._numBoneInfluencers === value) {
  16215. return;
  16216. }
  16217. this._numBoneInfluencers = value;
  16218. this._markSubMeshesAsAttributesDirty();
  16219. },
  16220. enumerable: true,
  16221. configurable: true
  16222. });
  16223. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  16224. get: function () {
  16225. return this._applyFog;
  16226. },
  16227. set: function (value) {
  16228. if (this._applyFog === value) {
  16229. return;
  16230. }
  16231. this._applyFog = value;
  16232. this._markSubMeshesAsMiscDirty();
  16233. },
  16234. enumerable: true,
  16235. configurable: true
  16236. });
  16237. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  16238. get: function () {
  16239. return this._layerMask;
  16240. },
  16241. set: function (value) {
  16242. if (value === this._layerMask) {
  16243. return;
  16244. }
  16245. this._layerMask = value;
  16246. this._resyncLightSources();
  16247. },
  16248. enumerable: true,
  16249. configurable: true
  16250. });
  16251. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  16252. get: function () {
  16253. return this._collisionMask;
  16254. },
  16255. set: function (mask) {
  16256. this._collisionMask = !isNaN(mask) ? mask : -1;
  16257. },
  16258. enumerable: true,
  16259. configurable: true
  16260. });
  16261. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  16262. get: function () {
  16263. return this._collisionGroup;
  16264. },
  16265. set: function (mask) {
  16266. this._collisionGroup = !isNaN(mask) ? mask : -1;
  16267. },
  16268. enumerable: true,
  16269. configurable: true
  16270. });
  16271. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  16272. get: function () {
  16273. return null;
  16274. },
  16275. enumerable: true,
  16276. configurable: true
  16277. });
  16278. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  16279. get: function () {
  16280. return this._skeleton;
  16281. },
  16282. set: function (value) {
  16283. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  16284. this._skeleton._unregisterMeshWithPoseMatrix(this);
  16285. }
  16286. if (value && value.needInitialSkinMatrix) {
  16287. value._registerMeshWithPoseMatrix(this);
  16288. }
  16289. this._skeleton = value;
  16290. if (!this._skeleton) {
  16291. this._bonesTransformMatrices = null;
  16292. }
  16293. this._markSubMeshesAsAttributesDirty();
  16294. },
  16295. enumerable: true,
  16296. configurable: true
  16297. });
  16298. /**
  16299. * Boolean : true if the mesh has been disposed.
  16300. */
  16301. AbstractMesh.prototype.isDisposed = function () {
  16302. return this._isDisposed;
  16303. };
  16304. /**
  16305. * Returns the string "AbstractMesh"
  16306. */
  16307. AbstractMesh.prototype.getClassName = function () {
  16308. return "AbstractMesh";
  16309. };
  16310. /**
  16311. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  16312. */
  16313. AbstractMesh.prototype.toString = function (fullDetails) {
  16314. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  16315. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  16316. if (this._skeleton) {
  16317. ret += ", skeleton: " + this._skeleton.name;
  16318. }
  16319. if (fullDetails) {
  16320. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  16321. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  16322. }
  16323. return ret;
  16324. };
  16325. AbstractMesh.prototype._rebuild = function () {
  16326. if (this._occlusionQuery) {
  16327. this._occlusionQuery = null;
  16328. }
  16329. if (this._edgesRenderer) {
  16330. this._edgesRenderer._rebuild();
  16331. }
  16332. if (!this.subMeshes) {
  16333. return;
  16334. }
  16335. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  16336. var subMesh = _a[_i];
  16337. subMesh._rebuild();
  16338. }
  16339. };
  16340. AbstractMesh.prototype._resyncLightSources = function () {
  16341. this._lightSources.length = 0;
  16342. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  16343. var light = _a[_i];
  16344. if (!light.isEnabled()) {
  16345. continue;
  16346. }
  16347. if (light.canAffectMesh(this)) {
  16348. this._lightSources.push(light);
  16349. }
  16350. }
  16351. this._markSubMeshesAsLightDirty();
  16352. };
  16353. AbstractMesh.prototype._resyncLighSource = function (light) {
  16354. var isIn = light.isEnabled() && light.canAffectMesh(this);
  16355. var index = this._lightSources.indexOf(light);
  16356. if (index === -1) {
  16357. if (!isIn) {
  16358. return;
  16359. }
  16360. this._lightSources.push(light);
  16361. }
  16362. else {
  16363. if (isIn) {
  16364. return;
  16365. }
  16366. this._lightSources.splice(index, 1);
  16367. }
  16368. this._markSubMeshesAsLightDirty();
  16369. };
  16370. AbstractMesh.prototype._removeLightSource = function (light) {
  16371. var index = this._lightSources.indexOf(light);
  16372. if (index === -1) {
  16373. return;
  16374. }
  16375. this._lightSources.splice(index, 1);
  16376. this._markSubMeshesAsLightDirty();
  16377. };
  16378. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  16379. if (!this.subMeshes) {
  16380. return;
  16381. }
  16382. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  16383. var subMesh = _a[_i];
  16384. if (subMesh._materialDefines) {
  16385. func(subMesh._materialDefines);
  16386. }
  16387. }
  16388. };
  16389. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  16390. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  16391. };
  16392. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  16393. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  16394. };
  16395. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  16396. if (!this.subMeshes) {
  16397. return;
  16398. }
  16399. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  16400. var subMesh = _a[_i];
  16401. var material = subMesh.getMaterial();
  16402. if (material) {
  16403. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  16404. }
  16405. }
  16406. };
  16407. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  16408. /**
  16409. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16410. * Default : (1.0, 1.0, 1.0)
  16411. */
  16412. get: function () {
  16413. return this._scaling;
  16414. },
  16415. /**
  16416. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16417. * Default : (1.0, 1.0, 1.0)
  16418. */
  16419. set: function (newScaling) {
  16420. this._scaling = newScaling;
  16421. if (this.physicsImpostor) {
  16422. this.physicsImpostor.forceUpdate();
  16423. }
  16424. },
  16425. enumerable: true,
  16426. configurable: true
  16427. });
  16428. // Methods
  16429. /**
  16430. * Disables the mesh edger rendering mode.
  16431. * Returns the AbstractMesh.
  16432. */
  16433. AbstractMesh.prototype.disableEdgesRendering = function () {
  16434. if (this._edgesRenderer) {
  16435. this._edgesRenderer.dispose();
  16436. this._edgesRenderer = null;
  16437. }
  16438. return this;
  16439. };
  16440. /**
  16441. * Enables the edge rendering mode on the mesh.
  16442. * This mode makes the mesh edges visible.
  16443. * Returns the AbstractMesh.
  16444. */
  16445. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  16446. if (epsilon === void 0) { epsilon = 0.95; }
  16447. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  16448. this.disableEdgesRendering();
  16449. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  16450. return this;
  16451. };
  16452. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  16453. /**
  16454. * Returns true if the mesh is blocked. Used by the class Mesh.
  16455. * Returns the boolean `false` by default.
  16456. */
  16457. get: function () {
  16458. return false;
  16459. },
  16460. enumerable: true,
  16461. configurable: true
  16462. });
  16463. /**
  16464. * Returns the mesh itself by default, used by the class Mesh.
  16465. * Returned type : AbstractMesh
  16466. */
  16467. AbstractMesh.prototype.getLOD = function (camera) {
  16468. return this;
  16469. };
  16470. /**
  16471. * Returns 0 by default, used by the class Mesh.
  16472. * Returns an integer.
  16473. */
  16474. AbstractMesh.prototype.getTotalVertices = function () {
  16475. return 0;
  16476. };
  16477. /**
  16478. * Returns null by default, used by the class Mesh.
  16479. * Returned type : integer array
  16480. */
  16481. AbstractMesh.prototype.getIndices = function () {
  16482. return null;
  16483. };
  16484. /**
  16485. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  16486. * Returned type : float array or Float32Array
  16487. */
  16488. AbstractMesh.prototype.getVerticesData = function (kind) {
  16489. return null;
  16490. };
  16491. /**
  16492. * Sets the vertex data of the mesh geometry for the requested `kind`.
  16493. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  16494. * The `data` are either a numeric array either a Float32Array.
  16495. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  16496. * 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).
  16497. * Note that a new underlying VertexBuffer object is created each call.
  16498. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  16499. *
  16500. * Possible `kind` values :
  16501. * - BABYLON.VertexBuffer.PositionKind
  16502. * - BABYLON.VertexBuffer.UVKind
  16503. * - BABYLON.VertexBuffer.UV2Kind
  16504. * - BABYLON.VertexBuffer.UV3Kind
  16505. * - BABYLON.VertexBuffer.UV4Kind
  16506. * - BABYLON.VertexBuffer.UV5Kind
  16507. * - BABYLON.VertexBuffer.UV6Kind
  16508. * - BABYLON.VertexBuffer.ColorKind
  16509. * - BABYLON.VertexBuffer.MatricesIndicesKind
  16510. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  16511. * - BABYLON.VertexBuffer.MatricesWeightsKind
  16512. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  16513. *
  16514. * Returns the Mesh.
  16515. */
  16516. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  16517. return this;
  16518. };
  16519. /**
  16520. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  16521. * If the mesh has no geometry, it is simply returned as it is.
  16522. * The `data` are either a numeric array either a Float32Array.
  16523. * No new underlying VertexBuffer object is created.
  16524. * 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.
  16525. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  16526. *
  16527. * Possible `kind` values :
  16528. * - BABYLON.VertexBuffer.PositionKind
  16529. * - BABYLON.VertexBuffer.UVKind
  16530. * - BABYLON.VertexBuffer.UV2Kind
  16531. * - BABYLON.VertexBuffer.UV3Kind
  16532. * - BABYLON.VertexBuffer.UV4Kind
  16533. * - BABYLON.VertexBuffer.UV5Kind
  16534. * - BABYLON.VertexBuffer.UV6Kind
  16535. * - BABYLON.VertexBuffer.ColorKind
  16536. * - BABYLON.VertexBuffer.MatricesIndicesKind
  16537. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  16538. * - BABYLON.VertexBuffer.MatricesWeightsKind
  16539. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  16540. *
  16541. * Returns the Mesh.
  16542. */
  16543. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  16544. return this;
  16545. };
  16546. /**
  16547. * Sets the mesh indices.
  16548. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  16549. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  16550. * This method creates a new index buffer each call.
  16551. * Returns the Mesh.
  16552. */
  16553. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  16554. return this;
  16555. };
  16556. /** Returns false by default, used by the class Mesh.
  16557. * Returns a boolean
  16558. */
  16559. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  16560. return false;
  16561. };
  16562. /**
  16563. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  16564. * Returns a BoundingInfo
  16565. */
  16566. AbstractMesh.prototype.getBoundingInfo = function () {
  16567. if (this._masterMesh) {
  16568. return this._masterMesh.getBoundingInfo();
  16569. }
  16570. if (!this._boundingInfo) {
  16571. // this._boundingInfo is being created here
  16572. this._updateBoundingInfo();
  16573. }
  16574. // cannot be null.
  16575. return this._boundingInfo;
  16576. };
  16577. /**
  16578. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  16579. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  16580. */
  16581. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  16582. if (includeDescendants === void 0) { includeDescendants = true; }
  16583. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  16584. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  16585. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  16586. if (maxDimension === 0) {
  16587. return this;
  16588. }
  16589. var scale = 1 / maxDimension;
  16590. this.scaling.scaleInPlace(scale);
  16591. return this;
  16592. };
  16593. /**
  16594. * Sets a mesh new object BoundingInfo.
  16595. * Returns the AbstractMesh.
  16596. */
  16597. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  16598. this._boundingInfo = boundingInfo;
  16599. return this;
  16600. };
  16601. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  16602. get: function () {
  16603. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  16604. },
  16605. enumerable: true,
  16606. configurable: true
  16607. });
  16608. AbstractMesh.prototype._preActivate = function () {
  16609. };
  16610. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  16611. };
  16612. AbstractMesh.prototype._activate = function (renderId) {
  16613. this._renderId = renderId;
  16614. };
  16615. /**
  16616. * Returns the latest update of the World matrix
  16617. * Returns a Matrix.
  16618. */
  16619. AbstractMesh.prototype.getWorldMatrix = function () {
  16620. if (this._masterMesh) {
  16621. return this._masterMesh.getWorldMatrix();
  16622. }
  16623. return _super.prototype.getWorldMatrix.call(this);
  16624. };
  16625. /**
  16626. * Returns the latest update of the World matrix determinant.
  16627. */
  16628. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  16629. if (this._masterMesh) {
  16630. return this._masterMesh._getWorldMatrixDeterminant();
  16631. }
  16632. return _super.prototype._getWorldMatrixDeterminant.call(this);
  16633. };
  16634. // ================================== Point of View Movement =================================
  16635. /**
  16636. * Perform relative position change from the point of view of behind the front of the mesh.
  16637. * This is performed taking into account the meshes current rotation, so you do not have to care.
  16638. * Supports definition of mesh facing forward or backward.
  16639. * @param {number} amountRight
  16640. * @param {number} amountUp
  16641. * @param {number} amountForward
  16642. *
  16643. * Returns the AbstractMesh.
  16644. */
  16645. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  16646. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  16647. return this;
  16648. };
  16649. /**
  16650. * Calculate relative position change from the point of view of behind the front of the mesh.
  16651. * This is performed taking into account the meshes current rotation, so you do not have to care.
  16652. * Supports definition of mesh facing forward or backward.
  16653. * @param {number} amountRight
  16654. * @param {number} amountUp
  16655. * @param {number} amountForward
  16656. *
  16657. * Returns a new Vector3.
  16658. */
  16659. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  16660. var rotMatrix = new BABYLON.Matrix();
  16661. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16662. rotQuaternion.toRotationMatrix(rotMatrix);
  16663. var translationDelta = BABYLON.Vector3.Zero();
  16664. var defForwardMult = this.definedFacingForward ? -1 : 1;
  16665. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  16666. return translationDelta;
  16667. };
  16668. // ================================== Point of View Rotation =================================
  16669. /**
  16670. * Perform relative rotation change from the point of view of behind the front of the mesh.
  16671. * Supports definition of mesh facing forward or backward.
  16672. * @param {number} flipBack
  16673. * @param {number} twirlClockwise
  16674. * @param {number} tiltRight
  16675. *
  16676. * Returns the AbstractMesh.
  16677. */
  16678. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  16679. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  16680. return this;
  16681. };
  16682. /**
  16683. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  16684. * Supports definition of mesh facing forward or backward.
  16685. * @param {number} flipBack
  16686. * @param {number} twirlClockwise
  16687. * @param {number} tiltRight
  16688. *
  16689. * Returns a new Vector3.
  16690. */
  16691. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  16692. var defForwardMult = this.definedFacingForward ? 1 : -1;
  16693. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  16694. };
  16695. /**
  16696. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  16697. * @param includeDescendants Include bounding info from descendants as well (true by default).
  16698. */
  16699. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  16700. if (includeDescendants === void 0) { includeDescendants = true; }
  16701. this.computeWorldMatrix(true);
  16702. var min;
  16703. var max;
  16704. var boundingInfo = this.getBoundingInfo();
  16705. if (!this.subMeshes) {
  16706. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16707. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  16708. }
  16709. else {
  16710. min = boundingInfo.boundingBox.minimumWorld;
  16711. max = boundingInfo.boundingBox.maximumWorld;
  16712. }
  16713. if (includeDescendants) {
  16714. var descendants = this.getDescendants(false);
  16715. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  16716. var descendant = descendants_1[_i];
  16717. var childMesh = descendant;
  16718. childMesh.computeWorldMatrix(true);
  16719. //make sure we have the needed params to get mix and max
  16720. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  16721. continue;
  16722. }
  16723. var childBoundingInfo = childMesh.getBoundingInfo();
  16724. var boundingBox = childBoundingInfo.boundingBox;
  16725. var minBox = boundingBox.minimumWorld;
  16726. var maxBox = boundingBox.maximumWorld;
  16727. BABYLON.Tools.CheckExtends(minBox, min, max);
  16728. BABYLON.Tools.CheckExtends(maxBox, min, max);
  16729. }
  16730. }
  16731. return {
  16732. min: min,
  16733. max: max
  16734. };
  16735. };
  16736. /**
  16737. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  16738. * Returns the AbstractMesh.
  16739. */
  16740. AbstractMesh.prototype._updateBoundingInfo = function () {
  16741. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  16742. this._boundingInfo.update(this.worldMatrixFromCache);
  16743. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  16744. return this;
  16745. };
  16746. /**
  16747. * Update a mesh's children BoundingInfo objects only.
  16748. * Returns the AbstractMesh.
  16749. */
  16750. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  16751. if (!this.subMeshes) {
  16752. return this;
  16753. }
  16754. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  16755. var subMesh = this.subMeshes[subIndex];
  16756. if (!subMesh.IsGlobal) {
  16757. subMesh.updateBoundingInfo(matrix);
  16758. }
  16759. }
  16760. return this;
  16761. };
  16762. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  16763. // Bounding info
  16764. this._updateBoundingInfo();
  16765. };
  16766. /**
  16767. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  16768. * A mesh is in the frustum if its bounding box intersects the frustum.
  16769. * Boolean returned.
  16770. */
  16771. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  16772. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  16773. };
  16774. /**
  16775. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  16776. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  16777. * Boolean returned.
  16778. */
  16779. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16780. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  16781. ;
  16782. };
  16783. /**
  16784. * True if the mesh intersects another mesh or a SolidParticle object.
  16785. * 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)
  16786. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  16787. * Returns a boolean.
  16788. */
  16789. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  16790. if (precise === void 0) { precise = false; }
  16791. if (!this._boundingInfo || !mesh._boundingInfo) {
  16792. return false;
  16793. }
  16794. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  16795. return true;
  16796. }
  16797. if (includeDescendants) {
  16798. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  16799. var child = _a[_i];
  16800. if (child.intersectsMesh(mesh, precise, true)) {
  16801. return true;
  16802. }
  16803. }
  16804. }
  16805. return false;
  16806. };
  16807. /**
  16808. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  16809. * Returns a boolean.
  16810. */
  16811. AbstractMesh.prototype.intersectsPoint = function (point) {
  16812. if (!this._boundingInfo) {
  16813. return false;
  16814. }
  16815. return this._boundingInfo.intersectsPoint(point);
  16816. };
  16817. AbstractMesh.prototype.getPhysicsImpostor = function () {
  16818. return this.physicsImpostor;
  16819. };
  16820. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  16821. if (camera === void 0) { camera = null; }
  16822. if (!camera) {
  16823. camera = this.getScene().activeCamera;
  16824. }
  16825. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  16826. };
  16827. /**
  16828. * Returns the distance from the mesh to the active camera.
  16829. * Returns a float.
  16830. */
  16831. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  16832. if (camera === void 0) { camera = null; }
  16833. if (!camera) {
  16834. camera = this.getScene().activeCamera;
  16835. }
  16836. return this.absolutePosition.subtract(camera.position).length();
  16837. };
  16838. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  16839. if (!this.physicsImpostor) {
  16840. return this;
  16841. }
  16842. this.physicsImpostor.applyImpulse(force, contactPoint);
  16843. return this;
  16844. };
  16845. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  16846. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  16847. return this;
  16848. }
  16849. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  16850. mainPivot: pivot1,
  16851. connectedPivot: pivot2,
  16852. nativeParams: options
  16853. });
  16854. return this;
  16855. };
  16856. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  16857. // Collisions
  16858. /**
  16859. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  16860. * Default `false`.
  16861. */
  16862. get: function () {
  16863. return this._checkCollisions;
  16864. },
  16865. set: function (collisionEnabled) {
  16866. this._checkCollisions = collisionEnabled;
  16867. if (this.getScene().workerCollisions) {
  16868. this.getScene().collisionCoordinator.onMeshUpdated(this);
  16869. }
  16870. },
  16871. enumerable: true,
  16872. configurable: true
  16873. });
  16874. Object.defineProperty(AbstractMesh.prototype, "collider", {
  16875. /**
  16876. * Gets Collider object used to compute collisions (not physics)
  16877. */
  16878. get: function () {
  16879. return this._collider;
  16880. },
  16881. enumerable: true,
  16882. configurable: true
  16883. });
  16884. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  16885. var globalPosition = this.getAbsolutePosition();
  16886. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  16887. if (!this._collider) {
  16888. this._collider = new BABYLON.Collider();
  16889. }
  16890. this._collider._radius = this.ellipsoid;
  16891. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  16892. return this;
  16893. };
  16894. // Submeshes octree
  16895. /**
  16896. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  16897. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  16898. * Returns an Octree of submeshes.
  16899. */
  16900. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  16901. if (maxCapacity === void 0) { maxCapacity = 64; }
  16902. if (maxDepth === void 0) { maxDepth = 2; }
  16903. if (!this._submeshesOctree) {
  16904. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  16905. }
  16906. this.computeWorldMatrix(true);
  16907. var boundingInfo = this.getBoundingInfo();
  16908. // Update octree
  16909. var bbox = boundingInfo.boundingBox;
  16910. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  16911. return this._submeshesOctree;
  16912. };
  16913. // Collisions
  16914. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  16915. this._generatePointsArray();
  16916. if (!this._positions) {
  16917. return this;
  16918. }
  16919. // Transformation
  16920. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  16921. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  16922. subMesh._lastColliderWorldVertices = [];
  16923. subMesh._trianglePlanes = [];
  16924. var start = subMesh.verticesStart;
  16925. var end = (subMesh.verticesStart + subMesh.verticesCount);
  16926. for (var i = start; i < end; i++) {
  16927. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  16928. }
  16929. }
  16930. // Collide
  16931. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  16932. if (collider.collisionFound) {
  16933. collider.collidedMesh = this;
  16934. }
  16935. return this;
  16936. };
  16937. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  16938. var subMeshes;
  16939. var len;
  16940. // Octrees
  16941. if (this._submeshesOctree && this.useOctreeForCollisions) {
  16942. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  16943. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  16944. len = intersections.length;
  16945. subMeshes = intersections.data;
  16946. }
  16947. else {
  16948. subMeshes = this.subMeshes;
  16949. len = subMeshes.length;
  16950. }
  16951. for (var index = 0; index < len; index++) {
  16952. var subMesh = subMeshes[index];
  16953. // Bounding test
  16954. if (len > 1 && !subMesh._checkCollision(collider))
  16955. continue;
  16956. this._collideForSubMesh(subMesh, transformMatrix, collider);
  16957. }
  16958. return this;
  16959. };
  16960. AbstractMesh.prototype._checkCollision = function (collider) {
  16961. // Bounding box test
  16962. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  16963. return this;
  16964. // Transformation matrix
  16965. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  16966. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  16967. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  16968. return this;
  16969. };
  16970. // Picking
  16971. AbstractMesh.prototype._generatePointsArray = function () {
  16972. return false;
  16973. };
  16974. /**
  16975. * Checks if the passed Ray intersects with the mesh.
  16976. * Returns an object PickingInfo.
  16977. */
  16978. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  16979. var pickingInfo = new BABYLON.PickingInfo();
  16980. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  16981. return pickingInfo;
  16982. }
  16983. if (!this._generatePointsArray()) {
  16984. return pickingInfo;
  16985. }
  16986. var intersectInfo = null;
  16987. // Octrees
  16988. var subMeshes;
  16989. var len;
  16990. if (this._submeshesOctree && this.useOctreeForPicking) {
  16991. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  16992. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  16993. len = intersections.length;
  16994. subMeshes = intersections.data;
  16995. }
  16996. else {
  16997. subMeshes = this.subMeshes;
  16998. len = subMeshes.length;
  16999. }
  17000. for (var index = 0; index < len; index++) {
  17001. var subMesh = subMeshes[index];
  17002. // Bounding test
  17003. if (len > 1 && !subMesh.canIntersects(ray))
  17004. continue;
  17005. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  17006. if (currentIntersectInfo) {
  17007. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  17008. intersectInfo = currentIntersectInfo;
  17009. intersectInfo.subMeshId = index;
  17010. if (fastCheck) {
  17011. break;
  17012. }
  17013. }
  17014. }
  17015. }
  17016. if (intersectInfo) {
  17017. // Get picked point
  17018. var world = this.getWorldMatrix();
  17019. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  17020. var direction = ray.direction.clone();
  17021. direction = direction.scale(intersectInfo.distance);
  17022. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  17023. var pickedPoint = worldOrigin.add(worldDirection);
  17024. // Return result
  17025. pickingInfo.hit = true;
  17026. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  17027. pickingInfo.pickedPoint = pickedPoint;
  17028. pickingInfo.pickedMesh = this;
  17029. pickingInfo.bu = intersectInfo.bu || 0;
  17030. pickingInfo.bv = intersectInfo.bv || 0;
  17031. pickingInfo.faceId = intersectInfo.faceId;
  17032. pickingInfo.subMeshId = intersectInfo.subMeshId;
  17033. return pickingInfo;
  17034. }
  17035. return pickingInfo;
  17036. };
  17037. /**
  17038. * Clones the mesh, used by the class Mesh.
  17039. * Just returns `null` for an AbstractMesh.
  17040. */
  17041. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17042. return null;
  17043. };
  17044. /**
  17045. * Disposes all the mesh submeshes.
  17046. * Returns the AbstractMesh.
  17047. */
  17048. AbstractMesh.prototype.releaseSubMeshes = function () {
  17049. if (this.subMeshes) {
  17050. while (this.subMeshes.length) {
  17051. this.subMeshes[0].dispose();
  17052. }
  17053. }
  17054. else {
  17055. this.subMeshes = new Array();
  17056. }
  17057. return this;
  17058. };
  17059. /**
  17060. * Disposes the AbstractMesh.
  17061. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  17062. * Returns nothing.
  17063. */
  17064. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17065. var _this = this;
  17066. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17067. var index;
  17068. // Action manager
  17069. if (this.actionManager !== undefined && this.actionManager !== null) {
  17070. this.actionManager.dispose();
  17071. this.actionManager = null;
  17072. }
  17073. // Skeleton
  17074. this.skeleton = null;
  17075. // Physics
  17076. if (this.physicsImpostor) {
  17077. this.physicsImpostor.dispose();
  17078. }
  17079. // Intersections in progress
  17080. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  17081. var other = this._intersectionsInProgress[index];
  17082. var pos = other._intersectionsInProgress.indexOf(this);
  17083. other._intersectionsInProgress.splice(pos, 1);
  17084. }
  17085. this._intersectionsInProgress = [];
  17086. // Lights
  17087. var lights = this.getScene().lights;
  17088. lights.forEach(function (light) {
  17089. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  17090. if (meshIndex !== -1) {
  17091. light.includedOnlyMeshes.splice(meshIndex, 1);
  17092. }
  17093. meshIndex = light.excludedMeshes.indexOf(_this);
  17094. if (meshIndex !== -1) {
  17095. light.excludedMeshes.splice(meshIndex, 1);
  17096. }
  17097. // Shadow generators
  17098. var generator = light.getShadowGenerator();
  17099. if (generator) {
  17100. var shadowMap = generator.getShadowMap();
  17101. if (shadowMap && shadowMap.renderList) {
  17102. meshIndex = shadowMap.renderList.indexOf(_this);
  17103. if (meshIndex !== -1) {
  17104. shadowMap.renderList.splice(meshIndex, 1);
  17105. }
  17106. }
  17107. }
  17108. });
  17109. // Edges
  17110. if (this._edgesRenderer) {
  17111. this._edgesRenderer.dispose();
  17112. this._edgesRenderer = null;
  17113. }
  17114. // SubMeshes
  17115. if (this.getClassName() !== "InstancedMesh") {
  17116. this.releaseSubMeshes();
  17117. }
  17118. // Octree
  17119. var sceneOctree = this.getScene().selectionOctree;
  17120. if (sceneOctree !== undefined && sceneOctree !== null) {
  17121. var index = sceneOctree.dynamicContent.indexOf(this);
  17122. if (index !== -1) {
  17123. sceneOctree.dynamicContent.splice(index, 1);
  17124. }
  17125. }
  17126. // Query
  17127. var engine = this.getScene().getEngine();
  17128. if (this._occlusionQuery) {
  17129. this._isOcclusionQueryInProgress = false;
  17130. engine.deleteQuery(this._occlusionQuery);
  17131. this._occlusionQuery = null;
  17132. }
  17133. // Engine
  17134. engine.wipeCaches();
  17135. // Remove from scene
  17136. this.getScene().removeMesh(this);
  17137. if (disposeMaterialAndTextures) {
  17138. if (this.material) {
  17139. this.material.dispose(false, true);
  17140. }
  17141. }
  17142. if (!doNotRecurse) {
  17143. // Particles
  17144. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  17145. if (this.getScene().particleSystems[index].emitter === this) {
  17146. this.getScene().particleSystems[index].dispose();
  17147. index--;
  17148. }
  17149. }
  17150. }
  17151. // facet data
  17152. if (this._facetDataEnabled) {
  17153. this.disableFacetData();
  17154. }
  17155. this.onAfterWorldMatrixUpdateObservable.clear();
  17156. this.onCollideObservable.clear();
  17157. this.onCollisionPositionChangeObservable.clear();
  17158. this._isDisposed = true;
  17159. _super.prototype.dispose.call(this, doNotRecurse);
  17160. };
  17161. /**
  17162. * Adds the passed mesh as a child to the current mesh.
  17163. * Returns the AbstractMesh.
  17164. */
  17165. AbstractMesh.prototype.addChild = function (mesh) {
  17166. mesh.setParent(this);
  17167. return this;
  17168. };
  17169. /**
  17170. * Removes the passed mesh from the current mesh children list.
  17171. * Returns the AbstractMesh.
  17172. */
  17173. AbstractMesh.prototype.removeChild = function (mesh) {
  17174. mesh.setParent(null);
  17175. return this;
  17176. };
  17177. // Facet data
  17178. /**
  17179. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  17180. * Returns the AbstractMesh.
  17181. */
  17182. AbstractMesh.prototype._initFacetData = function () {
  17183. if (!this._facetNormals) {
  17184. this._facetNormals = new Array();
  17185. }
  17186. if (!this._facetPositions) {
  17187. this._facetPositions = new Array();
  17188. }
  17189. if (!this._facetPartitioning) {
  17190. this._facetPartitioning = new Array();
  17191. }
  17192. this._facetNb = (this.getIndices().length / 3) | 0;
  17193. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  17194. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  17195. for (var f = 0; f < this._facetNb; f++) {
  17196. this._facetNormals[f] = BABYLON.Vector3.Zero();
  17197. this._facetPositions[f] = BABYLON.Vector3.Zero();
  17198. }
  17199. this._facetDataEnabled = true;
  17200. return this;
  17201. };
  17202. /**
  17203. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  17204. * This method can be called within the render loop.
  17205. * 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.
  17206. * Returns the AbstractMesh.
  17207. */
  17208. AbstractMesh.prototype.updateFacetData = function () {
  17209. if (!this._facetDataEnabled) {
  17210. this._initFacetData();
  17211. }
  17212. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17213. var indices = this.getIndices();
  17214. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17215. var bInfo = this.getBoundingInfo();
  17216. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  17217. // init arrays, matrix and sort function on first call
  17218. this._facetDepthSortEnabled = true;
  17219. if (indices instanceof Uint16Array) {
  17220. this._depthSortedIndices = new Uint16Array(indices);
  17221. }
  17222. else if (indices instanceof Uint32Array) {
  17223. this._depthSortedIndices = new Uint32Array(indices);
  17224. }
  17225. else {
  17226. var needs32bits = false;
  17227. for (var i = 0; i < indices.length; i++) {
  17228. if (indices[i] > 65535) {
  17229. needs32bits = true;
  17230. break;
  17231. }
  17232. }
  17233. if (needs32bits) {
  17234. this._depthSortedIndices = new Uint32Array(indices);
  17235. }
  17236. else {
  17237. this._depthSortedIndices = new Uint16Array(indices);
  17238. }
  17239. }
  17240. this._facetDepthSortFunction = function (f1, f2) {
  17241. return (f2.sqDistance - f1.sqDistance);
  17242. };
  17243. if (!this._facetDepthSortFrom) {
  17244. var camera = this.getScene().activeCamera;
  17245. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  17246. }
  17247. this._depthSortedFacets = [];
  17248. for (var f = 0; f < this._facetNb; f++) {
  17249. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  17250. this._depthSortedFacets.push(depthSortedFacet);
  17251. }
  17252. this._invertedMatrix = BABYLON.Matrix.Identity();
  17253. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  17254. }
  17255. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  17256. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  17257. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  17258. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  17259. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  17260. this._subDiv.max = this._partitioningSubdivisions;
  17261. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  17262. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  17263. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  17264. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  17265. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  17266. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  17267. // set the parameters for ComputeNormals()
  17268. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  17269. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  17270. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  17271. this._facetParameters.bInfo = bInfo;
  17272. this._facetParameters.bbSize = this._bbSize;
  17273. this._facetParameters.subDiv = this._subDiv;
  17274. this._facetParameters.ratio = this.partitioningBBoxRatio;
  17275. this._facetParameters.depthSort = this._facetDepthSort;
  17276. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  17277. this.computeWorldMatrix(true);
  17278. this._worldMatrix.invertToRef(this._invertedMatrix);
  17279. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  17280. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  17281. }
  17282. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  17283. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  17284. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  17285. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  17286. var l = (this._depthSortedIndices.length / 3) | 0;
  17287. for (var f = 0; f < l; f++) {
  17288. var sind = this._depthSortedFacets[f].ind;
  17289. this._depthSortedIndices[f * 3] = indices[sind];
  17290. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  17291. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  17292. }
  17293. this.updateIndices(this._depthSortedIndices);
  17294. }
  17295. return this;
  17296. };
  17297. /**
  17298. * Returns the facetLocalNormals array.
  17299. * The normals are expressed in the mesh local space.
  17300. */
  17301. AbstractMesh.prototype.getFacetLocalNormals = function () {
  17302. if (!this._facetNormals) {
  17303. this.updateFacetData();
  17304. }
  17305. return this._facetNormals;
  17306. };
  17307. /**
  17308. * Returns the facetLocalPositions array.
  17309. * The facet positions are expressed in the mesh local space.
  17310. */
  17311. AbstractMesh.prototype.getFacetLocalPositions = function () {
  17312. if (!this._facetPositions) {
  17313. this.updateFacetData();
  17314. }
  17315. return this._facetPositions;
  17316. };
  17317. /**
  17318. * Returns the facetLocalPartioning array.
  17319. */
  17320. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  17321. if (!this._facetPartitioning) {
  17322. this.updateFacetData();
  17323. }
  17324. return this._facetPartitioning;
  17325. };
  17326. /**
  17327. * Returns the i-th facet position in the world system.
  17328. * This method allocates a new Vector3 per call.
  17329. */
  17330. AbstractMesh.prototype.getFacetPosition = function (i) {
  17331. var pos = BABYLON.Vector3.Zero();
  17332. this.getFacetPositionToRef(i, pos);
  17333. return pos;
  17334. };
  17335. /**
  17336. * Sets the reference Vector3 with the i-th facet position in the world system.
  17337. * Returns the AbstractMesh.
  17338. */
  17339. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  17340. var localPos = (this.getFacetLocalPositions())[i];
  17341. var world = this.getWorldMatrix();
  17342. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  17343. return this;
  17344. };
  17345. /**
  17346. * Returns the i-th facet normal in the world system.
  17347. * This method allocates a new Vector3 per call.
  17348. */
  17349. AbstractMesh.prototype.getFacetNormal = function (i) {
  17350. var norm = BABYLON.Vector3.Zero();
  17351. this.getFacetNormalToRef(i, norm);
  17352. return norm;
  17353. };
  17354. /**
  17355. * Sets the reference Vector3 with the i-th facet normal in the world system.
  17356. * Returns the AbstractMesh.
  17357. */
  17358. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  17359. var localNorm = (this.getFacetLocalNormals())[i];
  17360. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  17361. return this;
  17362. };
  17363. /**
  17364. * 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).
  17365. */
  17366. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  17367. var bInfo = this.getBoundingInfo();
  17368. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  17369. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  17370. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  17371. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  17372. return null;
  17373. }
  17374. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  17375. };
  17376. /**
  17377. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  17378. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  17379. * 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.
  17380. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  17381. * 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.
  17382. */
  17383. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  17384. if (checkFace === void 0) { checkFace = false; }
  17385. if (facing === void 0) { facing = true; }
  17386. var world = this.getWorldMatrix();
  17387. var invMat = BABYLON.Tmp.Matrix[5];
  17388. world.invertToRef(invMat);
  17389. var invVect = BABYLON.Tmp.Vector3[8];
  17390. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  17391. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  17392. if (projected) {
  17393. // tranform the local computed projected vector to world coordinates
  17394. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  17395. }
  17396. return closest;
  17397. };
  17398. /**
  17399. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  17400. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  17401. * 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.
  17402. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  17403. * 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.
  17404. */
  17405. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  17406. if (checkFace === void 0) { checkFace = false; }
  17407. if (facing === void 0) { facing = true; }
  17408. var closest = null;
  17409. var tmpx = 0.0;
  17410. var tmpy = 0.0;
  17411. var tmpz = 0.0;
  17412. var d = 0.0; // tmp dot facet normal * facet position
  17413. var t0 = 0.0;
  17414. var projx = 0.0;
  17415. var projy = 0.0;
  17416. var projz = 0.0;
  17417. // Get all the facets in the same partitioning block than (x, y, z)
  17418. var facetPositions = this.getFacetLocalPositions();
  17419. var facetNormals = this.getFacetLocalNormals();
  17420. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  17421. if (!facetsInBlock) {
  17422. return null;
  17423. }
  17424. // Get the closest facet to (x, y, z)
  17425. var shortest = Number.MAX_VALUE; // init distance vars
  17426. var tmpDistance = shortest;
  17427. var fib; // current facet in the block
  17428. var norm; // current facet normal
  17429. var p0; // current facet barycenter position
  17430. // loop on all the facets in the current partitioning block
  17431. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  17432. fib = facetsInBlock[idx];
  17433. norm = facetNormals[fib];
  17434. p0 = facetPositions[fib];
  17435. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  17436. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  17437. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  17438. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  17439. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  17440. projx = x + norm.x * t0;
  17441. projy = y + norm.y * t0;
  17442. projz = z + norm.z * t0;
  17443. tmpx = projx - x;
  17444. tmpy = projy - y;
  17445. tmpz = projz - z;
  17446. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  17447. if (tmpDistance < shortest) {
  17448. shortest = tmpDistance;
  17449. closest = fib;
  17450. if (projected) {
  17451. projected.x = projx;
  17452. projected.y = projy;
  17453. projected.z = projz;
  17454. }
  17455. }
  17456. }
  17457. }
  17458. return closest;
  17459. };
  17460. /**
  17461. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  17462. */
  17463. AbstractMesh.prototype.getFacetDataParameters = function () {
  17464. return this._facetParameters;
  17465. };
  17466. /**
  17467. * Disables the feature FacetData and frees the related memory.
  17468. * Returns the AbstractMesh.
  17469. */
  17470. AbstractMesh.prototype.disableFacetData = function () {
  17471. if (this._facetDataEnabled) {
  17472. this._facetDataEnabled = false;
  17473. this._facetPositions = new Array();
  17474. this._facetNormals = new Array();
  17475. this._facetPartitioning = new Array();
  17476. this._facetParameters = null;
  17477. this._depthSortedIndices = new Uint32Array(0);
  17478. }
  17479. return this;
  17480. };
  17481. /**
  17482. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  17483. * Returns the mesh.
  17484. */
  17485. AbstractMesh.prototype.updateIndices = function (indices) {
  17486. return this;
  17487. };
  17488. /**
  17489. * The mesh Geometry. Actually used by the Mesh object.
  17490. * Returns a blank geometry object.
  17491. */
  17492. /**
  17493. * Creates new normals data for the mesh.
  17494. * @param updatable.
  17495. */
  17496. AbstractMesh.prototype.createNormals = function (updatable) {
  17497. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17498. var indices = this.getIndices();
  17499. var normals;
  17500. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17501. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17502. }
  17503. else {
  17504. normals = [];
  17505. }
  17506. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  17507. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  17508. };
  17509. /**
  17510. * Align the mesh with a normal.
  17511. * Returns the mesh.
  17512. */
  17513. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  17514. if (!upDirection) {
  17515. upDirection = BABYLON.Axis.Y;
  17516. }
  17517. var axisX = BABYLON.Tmp.Vector3[0];
  17518. var axisZ = BABYLON.Tmp.Vector3[1];
  17519. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  17520. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  17521. if (this.rotationQuaternion) {
  17522. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  17523. }
  17524. else {
  17525. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  17526. }
  17527. return this;
  17528. };
  17529. AbstractMesh.prototype.checkOcclusionQuery = function () {
  17530. var engine = this.getEngine();
  17531. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  17532. this._isOccluded = false;
  17533. return;
  17534. }
  17535. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  17536. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  17537. if (isOcclusionQueryAvailable) {
  17538. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  17539. this._isOcclusionQueryInProgress = false;
  17540. this._occlusionInternalRetryCounter = 0;
  17541. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  17542. }
  17543. else {
  17544. this._occlusionInternalRetryCounter++;
  17545. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  17546. this._isOcclusionQueryInProgress = false;
  17547. this._occlusionInternalRetryCounter = 0;
  17548. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  17549. // if strict continue the last state of the object.
  17550. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  17551. }
  17552. else {
  17553. return;
  17554. }
  17555. }
  17556. }
  17557. var scene = this.getScene();
  17558. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  17559. if (!this._occlusionQuery) {
  17560. this._occlusionQuery = engine.createQuery();
  17561. }
  17562. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  17563. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  17564. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  17565. this._isOcclusionQueryInProgress = true;
  17566. };
  17567. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  17568. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  17569. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  17570. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  17571. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  17572. return AbstractMesh;
  17573. }(BABYLON.TransformNode));
  17574. BABYLON.AbstractMesh = AbstractMesh;
  17575. })(BABYLON || (BABYLON = {}));
  17576. //# sourceMappingURL=babylon.abstractMesh.js.map
  17577. var BABYLON;
  17578. (function (BABYLON) {
  17579. var Light = /** @class */ (function (_super) {
  17580. __extends(Light, _super);
  17581. /**
  17582. * Creates a Light object in the scene.
  17583. * Documentation : http://doc.babylonjs.com/tutorials/lights
  17584. */
  17585. function Light(name, scene) {
  17586. var _this = _super.call(this, name, scene) || this;
  17587. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  17588. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  17589. _this.intensity = 1.0;
  17590. _this.range = Number.MAX_VALUE;
  17591. /**
  17592. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  17593. * of light.
  17594. */
  17595. _this._photometricScale = 1.0;
  17596. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  17597. _this._radius = 0.00001;
  17598. _this.renderPriority = 0;
  17599. /**
  17600. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  17601. * the current shadow generator.
  17602. */
  17603. _this.shadowEnabled = true;
  17604. _this._excludeWithLayerMask = 0;
  17605. _this._includeOnlyWithLayerMask = 0;
  17606. _this._lightmapMode = 0;
  17607. _this._excludedMeshesIds = new Array();
  17608. _this._includedOnlyMeshesIds = new Array();
  17609. _this.getScene().addLight(_this);
  17610. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  17611. _this._buildUniformLayout();
  17612. _this.includedOnlyMeshes = new Array();
  17613. _this.excludedMeshes = new Array();
  17614. _this._resyncMeshes();
  17615. return _this;
  17616. }
  17617. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  17618. /**
  17619. * If every light affecting the material is in this lightmapMode,
  17620. * material.lightmapTexture adds or multiplies
  17621. * (depends on material.useLightmapAsShadowmap)
  17622. * after every other light calculations.
  17623. */
  17624. get: function () {
  17625. return Light._LIGHTMAP_DEFAULT;
  17626. },
  17627. enumerable: true,
  17628. configurable: true
  17629. });
  17630. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  17631. /**
  17632. * material.lightmapTexture as only diffuse lighting from this light
  17633. * adds only specular lighting from this light
  17634. * adds dynamic shadows
  17635. */
  17636. get: function () {
  17637. return Light._LIGHTMAP_SPECULAR;
  17638. },
  17639. enumerable: true,
  17640. configurable: true
  17641. });
  17642. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  17643. /**
  17644. * material.lightmapTexture as only lighting
  17645. * no light calculation from this light
  17646. * only adds dynamic shadows from this light
  17647. */
  17648. get: function () {
  17649. return Light._LIGHTMAP_SHADOWSONLY;
  17650. },
  17651. enumerable: true,
  17652. configurable: true
  17653. });
  17654. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  17655. /**
  17656. * Each light type uses the default quantity according to its type:
  17657. * point/spot lights use luminous intensity
  17658. * directional lights use illuminance
  17659. */
  17660. get: function () {
  17661. return Light._INTENSITYMODE_AUTOMATIC;
  17662. },
  17663. enumerable: true,
  17664. configurable: true
  17665. });
  17666. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  17667. /**
  17668. * lumen (lm)
  17669. */
  17670. get: function () {
  17671. return Light._INTENSITYMODE_LUMINOUSPOWER;
  17672. },
  17673. enumerable: true,
  17674. configurable: true
  17675. });
  17676. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  17677. /**
  17678. * candela (lm/sr)
  17679. */
  17680. get: function () {
  17681. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  17682. },
  17683. enumerable: true,
  17684. configurable: true
  17685. });
  17686. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  17687. /**
  17688. * lux (lm/m^2)
  17689. */
  17690. get: function () {
  17691. return Light._INTENSITYMODE_ILLUMINANCE;
  17692. },
  17693. enumerable: true,
  17694. configurable: true
  17695. });
  17696. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  17697. /**
  17698. * nit (cd/m^2)
  17699. */
  17700. get: function () {
  17701. return Light._INTENSITYMODE_LUMINANCE;
  17702. },
  17703. enumerable: true,
  17704. configurable: true
  17705. });
  17706. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  17707. /**
  17708. * Light type const id of the point light.
  17709. */
  17710. get: function () {
  17711. return Light._LIGHTTYPEID_POINTLIGHT;
  17712. },
  17713. enumerable: true,
  17714. configurable: true
  17715. });
  17716. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  17717. /**
  17718. * Light type const id of the directional light.
  17719. */
  17720. get: function () {
  17721. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  17722. },
  17723. enumerable: true,
  17724. configurable: true
  17725. });
  17726. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  17727. /**
  17728. * Light type const id of the spot light.
  17729. */
  17730. get: function () {
  17731. return Light._LIGHTTYPEID_SPOTLIGHT;
  17732. },
  17733. enumerable: true,
  17734. configurable: true
  17735. });
  17736. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  17737. /**
  17738. * Light type const id of the hemispheric light.
  17739. */
  17740. get: function () {
  17741. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  17742. },
  17743. enumerable: true,
  17744. configurable: true
  17745. });
  17746. Object.defineProperty(Light.prototype, "intensityMode", {
  17747. /**
  17748. * Gets the photometric scale used to interpret the intensity.
  17749. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  17750. */
  17751. get: function () {
  17752. return this._intensityMode;
  17753. },
  17754. /**
  17755. * Sets the photometric scale used to interpret the intensity.
  17756. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  17757. */
  17758. set: function (value) {
  17759. this._intensityMode = value;
  17760. this._computePhotometricScale();
  17761. },
  17762. enumerable: true,
  17763. configurable: true
  17764. });
  17765. ;
  17766. ;
  17767. Object.defineProperty(Light.prototype, "radius", {
  17768. /**
  17769. * Gets the light radius used by PBR Materials to simulate soft area lights.
  17770. */
  17771. get: function () {
  17772. return this._radius;
  17773. },
  17774. /**
  17775. * sets the light radius used by PBR Materials to simulate soft area lights.
  17776. */
  17777. set: function (value) {
  17778. this._radius = value;
  17779. this._computePhotometricScale();
  17780. },
  17781. enumerable: true,
  17782. configurable: true
  17783. });
  17784. ;
  17785. ;
  17786. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  17787. get: function () {
  17788. return this._includedOnlyMeshes;
  17789. },
  17790. set: function (value) {
  17791. this._includedOnlyMeshes = value;
  17792. this._hookArrayForIncludedOnly(value);
  17793. },
  17794. enumerable: true,
  17795. configurable: true
  17796. });
  17797. Object.defineProperty(Light.prototype, "excludedMeshes", {
  17798. get: function () {
  17799. return this._excludedMeshes;
  17800. },
  17801. set: function (value) {
  17802. this._excludedMeshes = value;
  17803. this._hookArrayForExcluded(value);
  17804. },
  17805. enumerable: true,
  17806. configurable: true
  17807. });
  17808. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  17809. get: function () {
  17810. return this._excludeWithLayerMask;
  17811. },
  17812. set: function (value) {
  17813. this._excludeWithLayerMask = value;
  17814. this._resyncMeshes();
  17815. },
  17816. enumerable: true,
  17817. configurable: true
  17818. });
  17819. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  17820. get: function () {
  17821. return this._includeOnlyWithLayerMask;
  17822. },
  17823. set: function (value) {
  17824. this._includeOnlyWithLayerMask = value;
  17825. this._resyncMeshes();
  17826. },
  17827. enumerable: true,
  17828. configurable: true
  17829. });
  17830. Object.defineProperty(Light.prototype, "lightmapMode", {
  17831. get: function () {
  17832. return this._lightmapMode;
  17833. },
  17834. set: function (value) {
  17835. if (this._lightmapMode === value) {
  17836. return;
  17837. }
  17838. this._lightmapMode = value;
  17839. this._markMeshesAsLightDirty();
  17840. },
  17841. enumerable: true,
  17842. configurable: true
  17843. });
  17844. Light.prototype._buildUniformLayout = function () {
  17845. // Overridden
  17846. };
  17847. /**
  17848. * Returns the string "Light".
  17849. */
  17850. Light.prototype.getClassName = function () {
  17851. return "Light";
  17852. };
  17853. /**
  17854. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17855. */
  17856. Light.prototype.toString = function (fullDetails) {
  17857. var ret = "Name: " + this.name;
  17858. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  17859. if (this.animations) {
  17860. for (var i = 0; i < this.animations.length; i++) {
  17861. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  17862. }
  17863. }
  17864. if (fullDetails) {
  17865. }
  17866. return ret;
  17867. };
  17868. /**
  17869. * Set the enabled state of this node.
  17870. * @param {boolean} value - the new enabled state
  17871. * @see isEnabled
  17872. */
  17873. Light.prototype.setEnabled = function (value) {
  17874. _super.prototype.setEnabled.call(this, value);
  17875. this._resyncMeshes();
  17876. };
  17877. /**
  17878. * Returns the Light associated shadow generator.
  17879. */
  17880. Light.prototype.getShadowGenerator = function () {
  17881. return this._shadowGenerator;
  17882. };
  17883. /**
  17884. * Returns a Vector3, the absolute light position in the World.
  17885. */
  17886. Light.prototype.getAbsolutePosition = function () {
  17887. return BABYLON.Vector3.Zero();
  17888. };
  17889. Light.prototype.transferToEffect = function (effect, lightIndex) {
  17890. };
  17891. Light.prototype._getWorldMatrix = function () {
  17892. return BABYLON.Matrix.Identity();
  17893. };
  17894. /**
  17895. * Boolean : True if the light will affect the passed mesh.
  17896. */
  17897. Light.prototype.canAffectMesh = function (mesh) {
  17898. if (!mesh) {
  17899. return true;
  17900. }
  17901. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  17902. return false;
  17903. }
  17904. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  17905. return false;
  17906. }
  17907. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  17908. return false;
  17909. }
  17910. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  17911. return false;
  17912. }
  17913. return true;
  17914. };
  17915. /**
  17916. * Returns the light World matrix.
  17917. */
  17918. Light.prototype.getWorldMatrix = function () {
  17919. this._currentRenderId = this.getScene().getRenderId();
  17920. var worldMatrix = this._getWorldMatrix();
  17921. if (this.parent && this.parent.getWorldMatrix) {
  17922. if (!this._parentedWorldMatrix) {
  17923. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  17924. }
  17925. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  17926. this._markSyncedWithParent();
  17927. return this._parentedWorldMatrix;
  17928. }
  17929. return worldMatrix;
  17930. };
  17931. /**
  17932. * Sort function to order lights for rendering.
  17933. * @param a First Light object to compare to second.
  17934. * @param b Second Light object to compare first.
  17935. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  17936. */
  17937. Light.compareLightsPriority = function (a, b) {
  17938. //shadow-casting lights have priority over non-shadow-casting lights
  17939. //the renderPrioirty is a secondary sort criterion
  17940. if (a.shadowEnabled !== b.shadowEnabled) {
  17941. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  17942. }
  17943. return b.renderPriority - a.renderPriority;
  17944. };
  17945. /**
  17946. * Disposes the light.
  17947. */
  17948. Light.prototype.dispose = function () {
  17949. if (this._shadowGenerator) {
  17950. this._shadowGenerator.dispose();
  17951. this._shadowGenerator = null;
  17952. }
  17953. // Animations
  17954. this.getScene().stopAnimation(this);
  17955. this._uniformBuffer.dispose();
  17956. // Remove from scene
  17957. this.getScene().removeLight(this);
  17958. _super.prototype.dispose.call(this);
  17959. };
  17960. /**
  17961. * Returns the light type ID (integer).
  17962. */
  17963. Light.prototype.getTypeID = function () {
  17964. return 0;
  17965. };
  17966. /**
  17967. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  17968. */
  17969. Light.prototype.getScaledIntensity = function () {
  17970. return this._photometricScale * this.intensity;
  17971. };
  17972. /**
  17973. * Returns a new Light object, named "name", from the current one.
  17974. */
  17975. Light.prototype.clone = function (name) {
  17976. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  17977. if (!constructor) {
  17978. return null;
  17979. }
  17980. return BABYLON.SerializationHelper.Clone(constructor, this);
  17981. };
  17982. /**
  17983. * Serializes the current light into a Serialization object.
  17984. * Returns the serialized object.
  17985. */
  17986. Light.prototype.serialize = function () {
  17987. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  17988. // Type
  17989. serializationObject.type = this.getTypeID();
  17990. // Parent
  17991. if (this.parent) {
  17992. serializationObject.parentId = this.parent.id;
  17993. }
  17994. // Inclusion / exclusions
  17995. if (this.excludedMeshes.length > 0) {
  17996. serializationObject.excludedMeshesIds = [];
  17997. this.excludedMeshes.forEach(function (mesh) {
  17998. serializationObject.excludedMeshesIds.push(mesh.id);
  17999. });
  18000. }
  18001. if (this.includedOnlyMeshes.length > 0) {
  18002. serializationObject.includedOnlyMeshesIds = [];
  18003. this.includedOnlyMeshes.forEach(function (mesh) {
  18004. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  18005. });
  18006. }
  18007. // Animations
  18008. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  18009. serializationObject.ranges = this.serializeAnimationRanges();
  18010. return serializationObject;
  18011. };
  18012. /**
  18013. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  18014. * This new light is named "name" and added to the passed scene.
  18015. */
  18016. Light.GetConstructorFromName = function (type, name, scene) {
  18017. switch (type) {
  18018. case 0:
  18019. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  18020. case 1:
  18021. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  18022. case 2:
  18023. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  18024. case 3:
  18025. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  18026. }
  18027. return null;
  18028. };
  18029. /**
  18030. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  18031. */
  18032. Light.Parse = function (parsedLight, scene) {
  18033. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  18034. if (!constructor) {
  18035. return null;
  18036. }
  18037. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  18038. // Inclusion / exclusions
  18039. if (parsedLight.excludedMeshesIds) {
  18040. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  18041. }
  18042. if (parsedLight.includedOnlyMeshesIds) {
  18043. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  18044. }
  18045. // Parent
  18046. if (parsedLight.parentId) {
  18047. light._waitingParentId = parsedLight.parentId;
  18048. }
  18049. // Animations
  18050. if (parsedLight.animations) {
  18051. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  18052. var parsedAnimation = parsedLight.animations[animationIndex];
  18053. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18054. }
  18055. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  18056. }
  18057. if (parsedLight.autoAnimate) {
  18058. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  18059. }
  18060. return light;
  18061. };
  18062. Light.prototype._hookArrayForExcluded = function (array) {
  18063. var _this = this;
  18064. var oldPush = array.push;
  18065. array.push = function () {
  18066. var items = [];
  18067. for (var _i = 0; _i < arguments.length; _i++) {
  18068. items[_i] = arguments[_i];
  18069. }
  18070. var result = oldPush.apply(array, items);
  18071. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  18072. var item = items_1[_a];
  18073. item._resyncLighSource(_this);
  18074. }
  18075. return result;
  18076. };
  18077. var oldSplice = array.splice;
  18078. array.splice = function (index, deleteCount) {
  18079. var deleted = oldSplice.apply(array, [index, deleteCount]);
  18080. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  18081. var item = deleted_1[_i];
  18082. item._resyncLighSource(_this);
  18083. }
  18084. return deleted;
  18085. };
  18086. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  18087. var item = array_1[_i];
  18088. item._resyncLighSource(this);
  18089. }
  18090. };
  18091. Light.prototype._hookArrayForIncludedOnly = function (array) {
  18092. var _this = this;
  18093. var oldPush = array.push;
  18094. array.push = function () {
  18095. var items = [];
  18096. for (var _i = 0; _i < arguments.length; _i++) {
  18097. items[_i] = arguments[_i];
  18098. }
  18099. var result = oldPush.apply(array, items);
  18100. _this._resyncMeshes();
  18101. return result;
  18102. };
  18103. var oldSplice = array.splice;
  18104. array.splice = function (index, deleteCount) {
  18105. var deleted = oldSplice.apply(array, [index, deleteCount]);
  18106. _this._resyncMeshes();
  18107. return deleted;
  18108. };
  18109. this._resyncMeshes();
  18110. };
  18111. Light.prototype._resyncMeshes = function () {
  18112. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  18113. var mesh = _a[_i];
  18114. mesh._resyncLighSource(this);
  18115. }
  18116. };
  18117. Light.prototype._markMeshesAsLightDirty = function () {
  18118. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  18119. var mesh = _a[_i];
  18120. if (mesh._lightSources.indexOf(this) !== -1) {
  18121. mesh._markSubMeshesAsLightDirty();
  18122. }
  18123. }
  18124. };
  18125. /**
  18126. * Recomputes the cached photometric scale if needed.
  18127. */
  18128. Light.prototype._computePhotometricScale = function () {
  18129. this._photometricScale = this._getPhotometricScale();
  18130. this.getScene().resetCachedMaterial();
  18131. };
  18132. /**
  18133. * Returns the Photometric Scale according to the light type and intensity mode.
  18134. */
  18135. Light.prototype._getPhotometricScale = function () {
  18136. var photometricScale = 0.0;
  18137. var lightTypeID = this.getTypeID();
  18138. //get photometric mode
  18139. var photometricMode = this.intensityMode;
  18140. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  18141. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  18142. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  18143. }
  18144. else {
  18145. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  18146. }
  18147. }
  18148. //compute photometric scale
  18149. switch (lightTypeID) {
  18150. case Light.LIGHTTYPEID_POINTLIGHT:
  18151. case Light.LIGHTTYPEID_SPOTLIGHT:
  18152. switch (photometricMode) {
  18153. case Light.INTENSITYMODE_LUMINOUSPOWER:
  18154. photometricScale = 1.0 / (4.0 * Math.PI);
  18155. break;
  18156. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  18157. photometricScale = 1.0;
  18158. break;
  18159. case Light.INTENSITYMODE_LUMINANCE:
  18160. photometricScale = this.radius * this.radius;
  18161. break;
  18162. }
  18163. break;
  18164. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  18165. switch (photometricMode) {
  18166. case Light.INTENSITYMODE_ILLUMINANCE:
  18167. photometricScale = 1.0;
  18168. break;
  18169. case Light.INTENSITYMODE_LUMINANCE:
  18170. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  18171. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  18172. var apexAngleRadians = this.radius;
  18173. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  18174. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  18175. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  18176. photometricScale = solidAngle;
  18177. break;
  18178. }
  18179. break;
  18180. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  18181. // No fall off in hemisperic light.
  18182. photometricScale = 1.0;
  18183. break;
  18184. }
  18185. return photometricScale;
  18186. };
  18187. Light.prototype._reorderLightsInScene = function () {
  18188. var scene = this.getScene();
  18189. if (this._renderPriority != 0) {
  18190. scene.requireLightSorting = true;
  18191. }
  18192. this.getScene().sortLightsByPriority();
  18193. };
  18194. //lightmapMode Consts
  18195. Light._LIGHTMAP_DEFAULT = 0;
  18196. Light._LIGHTMAP_SPECULAR = 1;
  18197. Light._LIGHTMAP_SHADOWSONLY = 2;
  18198. // Intensity Mode Consts
  18199. Light._INTENSITYMODE_AUTOMATIC = 0;
  18200. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  18201. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  18202. Light._INTENSITYMODE_ILLUMINANCE = 3;
  18203. Light._INTENSITYMODE_LUMINANCE = 4;
  18204. // Light types ids const.
  18205. Light._LIGHTTYPEID_POINTLIGHT = 0;
  18206. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  18207. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  18208. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  18209. __decorate([
  18210. BABYLON.serializeAsColor3()
  18211. ], Light.prototype, "diffuse", void 0);
  18212. __decorate([
  18213. BABYLON.serializeAsColor3()
  18214. ], Light.prototype, "specular", void 0);
  18215. __decorate([
  18216. BABYLON.serialize()
  18217. ], Light.prototype, "intensity", void 0);
  18218. __decorate([
  18219. BABYLON.serialize()
  18220. ], Light.prototype, "range", void 0);
  18221. __decorate([
  18222. BABYLON.serialize()
  18223. ], Light.prototype, "intensityMode", null);
  18224. __decorate([
  18225. BABYLON.serialize()
  18226. ], Light.prototype, "radius", null);
  18227. __decorate([
  18228. BABYLON.serialize()
  18229. ], Light.prototype, "_renderPriority", void 0);
  18230. __decorate([
  18231. BABYLON.expandToProperty("_reorderLightsInScene")
  18232. ], Light.prototype, "renderPriority", void 0);
  18233. __decorate([
  18234. BABYLON.serialize()
  18235. ], Light.prototype, "shadowEnabled", void 0);
  18236. __decorate([
  18237. BABYLON.serialize("excludeWithLayerMask")
  18238. ], Light.prototype, "_excludeWithLayerMask", void 0);
  18239. __decorate([
  18240. BABYLON.serialize("includeOnlyWithLayerMask")
  18241. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  18242. __decorate([
  18243. BABYLON.serialize("lightmapMode")
  18244. ], Light.prototype, "_lightmapMode", void 0);
  18245. return Light;
  18246. }(BABYLON.Node));
  18247. BABYLON.Light = Light;
  18248. })(BABYLON || (BABYLON = {}));
  18249. //# sourceMappingURL=babylon.light.js.map
  18250. var BABYLON;
  18251. (function (BABYLON) {
  18252. var Camera = /** @class */ (function (_super) {
  18253. __extends(Camera, _super);
  18254. function Camera(name, position, scene) {
  18255. var _this = _super.call(this, name, scene) || this;
  18256. /**
  18257. * The vector the camera should consider as up.
  18258. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  18259. */
  18260. _this.upVector = BABYLON.Vector3.Up();
  18261. _this.orthoLeft = null;
  18262. _this.orthoRight = null;
  18263. _this.orthoBottom = null;
  18264. _this.orthoTop = null;
  18265. /**
  18266. * FOV is set in Radians. (default is 0.8)
  18267. */
  18268. _this.fov = 0.8;
  18269. _this.minZ = 1;
  18270. _this.maxZ = 10000.0;
  18271. _this.inertia = 0.9;
  18272. _this.mode = Camera.PERSPECTIVE_CAMERA;
  18273. _this.isIntermediate = false;
  18274. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  18275. /**
  18276. * Restricts the camera to viewing objects with the same layerMask.
  18277. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  18278. */
  18279. _this.layerMask = 0x0FFFFFFF;
  18280. /**
  18281. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  18282. */
  18283. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  18284. // Camera rig members
  18285. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  18286. _this._rigCameras = new Array();
  18287. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  18288. _this._skipRendering = false;
  18289. _this.customRenderTargets = new Array();
  18290. // Observables
  18291. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  18292. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  18293. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  18294. _this.onRestoreStateObservable = new BABYLON.Observable();
  18295. // Cache
  18296. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  18297. _this._projectionMatrix = new BABYLON.Matrix();
  18298. _this._doNotComputeProjectionMatrix = false;
  18299. _this._postProcesses = new Array();
  18300. _this._transformMatrix = BABYLON.Matrix.Zero();
  18301. _this._activeMeshes = new BABYLON.SmartArray(256);
  18302. _this._globalPosition = BABYLON.Vector3.Zero();
  18303. _this._refreshFrustumPlanes = true;
  18304. _this.getScene().addCamera(_this);
  18305. if (!_this.getScene().activeCamera) {
  18306. _this.getScene().activeCamera = _this;
  18307. }
  18308. _this.position = position;
  18309. return _this;
  18310. }
  18311. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  18312. get: function () {
  18313. return Camera._PERSPECTIVE_CAMERA;
  18314. },
  18315. enumerable: true,
  18316. configurable: true
  18317. });
  18318. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  18319. get: function () {
  18320. return Camera._ORTHOGRAPHIC_CAMERA;
  18321. },
  18322. enumerable: true,
  18323. configurable: true
  18324. });
  18325. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  18326. /**
  18327. * This is the default FOV mode for perspective cameras.
  18328. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  18329. *
  18330. */
  18331. get: function () {
  18332. return Camera._FOVMODE_VERTICAL_FIXED;
  18333. },
  18334. enumerable: true,
  18335. configurable: true
  18336. });
  18337. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  18338. /**
  18339. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  18340. *
  18341. */
  18342. get: function () {
  18343. return Camera._FOVMODE_HORIZONTAL_FIXED;
  18344. },
  18345. enumerable: true,
  18346. configurable: true
  18347. });
  18348. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  18349. get: function () {
  18350. return Camera._RIG_MODE_NONE;
  18351. },
  18352. enumerable: true,
  18353. configurable: true
  18354. });
  18355. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  18356. get: function () {
  18357. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  18358. },
  18359. enumerable: true,
  18360. configurable: true
  18361. });
  18362. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  18363. get: function () {
  18364. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  18365. },
  18366. enumerable: true,
  18367. configurable: true
  18368. });
  18369. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  18370. get: function () {
  18371. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  18372. },
  18373. enumerable: true,
  18374. configurable: true
  18375. });
  18376. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  18377. get: function () {
  18378. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  18379. },
  18380. enumerable: true,
  18381. configurable: true
  18382. });
  18383. Object.defineProperty(Camera, "RIG_MODE_VR", {
  18384. get: function () {
  18385. return Camera._RIG_MODE_VR;
  18386. },
  18387. enumerable: true,
  18388. configurable: true
  18389. });
  18390. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  18391. get: function () {
  18392. return Camera._RIG_MODE_WEBVR;
  18393. },
  18394. enumerable: true,
  18395. configurable: true
  18396. });
  18397. /**
  18398. * Store current camera state (fov, position, etc..)
  18399. */
  18400. Camera.prototype.storeState = function () {
  18401. this._stateStored = true;
  18402. this._storedFov = this.fov;
  18403. return this;
  18404. };
  18405. /**
  18406. * Restores the camera state values if it has been stored. You must call storeState() first
  18407. */
  18408. Camera.prototype._restoreStateValues = function () {
  18409. if (!this._stateStored) {
  18410. return false;
  18411. }
  18412. this.fov = this._storedFov;
  18413. return true;
  18414. };
  18415. /**
  18416. * Restored camera state. You must call storeState() first
  18417. */
  18418. Camera.prototype.restoreState = function () {
  18419. if (this._restoreStateValues()) {
  18420. this.onRestoreStateObservable.notifyObservers(this);
  18421. return true;
  18422. }
  18423. return false;
  18424. };
  18425. Camera.prototype.getClassName = function () {
  18426. return "Camera";
  18427. };
  18428. /**
  18429. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  18430. */
  18431. Camera.prototype.toString = function (fullDetails) {
  18432. var ret = "Name: " + this.name;
  18433. ret += ", type: " + this.getClassName();
  18434. if (this.animations) {
  18435. for (var i = 0; i < this.animations.length; i++) {
  18436. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  18437. }
  18438. }
  18439. if (fullDetails) {
  18440. }
  18441. return ret;
  18442. };
  18443. Object.defineProperty(Camera.prototype, "globalPosition", {
  18444. get: function () {
  18445. return this._globalPosition;
  18446. },
  18447. enumerable: true,
  18448. configurable: true
  18449. });
  18450. Camera.prototype.getActiveMeshes = function () {
  18451. return this._activeMeshes;
  18452. };
  18453. Camera.prototype.isActiveMesh = function (mesh) {
  18454. return (this._activeMeshes.indexOf(mesh) !== -1);
  18455. };
  18456. //Cache
  18457. Camera.prototype._initCache = function () {
  18458. _super.prototype._initCache.call(this);
  18459. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18460. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18461. this._cache.mode = undefined;
  18462. this._cache.minZ = undefined;
  18463. this._cache.maxZ = undefined;
  18464. this._cache.fov = undefined;
  18465. this._cache.fovMode = undefined;
  18466. this._cache.aspectRatio = undefined;
  18467. this._cache.orthoLeft = undefined;
  18468. this._cache.orthoRight = undefined;
  18469. this._cache.orthoBottom = undefined;
  18470. this._cache.orthoTop = undefined;
  18471. this._cache.renderWidth = undefined;
  18472. this._cache.renderHeight = undefined;
  18473. };
  18474. Camera.prototype._updateCache = function (ignoreParentClass) {
  18475. if (!ignoreParentClass) {
  18476. _super.prototype._updateCache.call(this);
  18477. }
  18478. this._cache.position.copyFrom(this.position);
  18479. this._cache.upVector.copyFrom(this.upVector);
  18480. };
  18481. // Synchronized
  18482. Camera.prototype._isSynchronized = function () {
  18483. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  18484. };
  18485. Camera.prototype._isSynchronizedViewMatrix = function () {
  18486. if (!_super.prototype._isSynchronized.call(this))
  18487. return false;
  18488. return this._cache.position.equals(this.position)
  18489. && this._cache.upVector.equals(this.upVector)
  18490. && this.isSynchronizedWithParent();
  18491. };
  18492. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  18493. var check = this._cache.mode === this.mode
  18494. && this._cache.minZ === this.minZ
  18495. && this._cache.maxZ === this.maxZ;
  18496. if (!check) {
  18497. return false;
  18498. }
  18499. var engine = this.getEngine();
  18500. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  18501. check = this._cache.fov === this.fov
  18502. && this._cache.fovMode === this.fovMode
  18503. && this._cache.aspectRatio === engine.getAspectRatio(this);
  18504. }
  18505. else {
  18506. check = this._cache.orthoLeft === this.orthoLeft
  18507. && this._cache.orthoRight === this.orthoRight
  18508. && this._cache.orthoBottom === this.orthoBottom
  18509. && this._cache.orthoTop === this.orthoTop
  18510. && this._cache.renderWidth === engine.getRenderWidth()
  18511. && this._cache.renderHeight === engine.getRenderHeight();
  18512. }
  18513. return check;
  18514. };
  18515. // Controls
  18516. Camera.prototype.attachControl = function (element, noPreventDefault) {
  18517. };
  18518. Camera.prototype.detachControl = function (element) {
  18519. };
  18520. Camera.prototype.update = function () {
  18521. this._checkInputs();
  18522. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18523. this._updateRigCameras();
  18524. }
  18525. };
  18526. Camera.prototype._checkInputs = function () {
  18527. this.onAfterCheckInputsObservable.notifyObservers(this);
  18528. };
  18529. Object.defineProperty(Camera.prototype, "rigCameras", {
  18530. get: function () {
  18531. return this._rigCameras;
  18532. },
  18533. enumerable: true,
  18534. configurable: true
  18535. });
  18536. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  18537. get: function () {
  18538. return this._rigPostProcess;
  18539. },
  18540. enumerable: true,
  18541. configurable: true
  18542. });
  18543. Camera.prototype._cascadePostProcessesToRigCams = function () {
  18544. // invalidate framebuffer
  18545. if (this._postProcesses.length > 0) {
  18546. this._postProcesses[0].markTextureDirty();
  18547. }
  18548. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  18549. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  18550. var cam = this._rigCameras[i];
  18551. var rigPostProcess = cam._rigPostProcess;
  18552. // for VR rig, there does not have to be a post process
  18553. if (rigPostProcess) {
  18554. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  18555. if (isPass) {
  18556. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  18557. cam.isIntermediate = this._postProcesses.length === 0;
  18558. }
  18559. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  18560. rigPostProcess.markTextureDirty();
  18561. }
  18562. else {
  18563. cam._postProcesses = this._postProcesses.slice(0);
  18564. }
  18565. }
  18566. };
  18567. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  18568. if (insertAt === void 0) { insertAt = null; }
  18569. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  18570. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  18571. return 0;
  18572. }
  18573. if (insertAt == null || insertAt < 0) {
  18574. this._postProcesses.push(postProcess);
  18575. }
  18576. else {
  18577. this._postProcesses.splice(insertAt, 0, postProcess);
  18578. }
  18579. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  18580. return this._postProcesses.indexOf(postProcess);
  18581. };
  18582. Camera.prototype.detachPostProcess = function (postProcess) {
  18583. var idx = this._postProcesses.indexOf(postProcess);
  18584. if (idx !== -1) {
  18585. this._postProcesses.splice(idx, 1);
  18586. }
  18587. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  18588. };
  18589. Camera.prototype.getWorldMatrix = function () {
  18590. if (!this._worldMatrix) {
  18591. this._worldMatrix = BABYLON.Matrix.Identity();
  18592. }
  18593. var viewMatrix = this.getViewMatrix();
  18594. viewMatrix.invertToRef(this._worldMatrix);
  18595. return this._worldMatrix;
  18596. };
  18597. Camera.prototype._getViewMatrix = function () {
  18598. return BABYLON.Matrix.Identity();
  18599. };
  18600. Camera.prototype.getViewMatrix = function (force) {
  18601. if (!force && this._isSynchronizedViewMatrix()) {
  18602. return this._computedViewMatrix;
  18603. }
  18604. this.updateCache();
  18605. this._computedViewMatrix = this._getViewMatrix();
  18606. this._currentRenderId = this.getScene().getRenderId();
  18607. this._refreshFrustumPlanes = true;
  18608. if (!this.parent || !this.parent.getWorldMatrix) {
  18609. this._globalPosition.copyFrom(this.position);
  18610. }
  18611. else {
  18612. if (!this._worldMatrix) {
  18613. this._worldMatrix = BABYLON.Matrix.Identity();
  18614. }
  18615. this._computedViewMatrix.invertToRef(this._worldMatrix);
  18616. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  18617. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  18618. this._computedViewMatrix.invert();
  18619. this._markSyncedWithParent();
  18620. }
  18621. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  18622. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  18623. }
  18624. this.onViewMatrixChangedObservable.notifyObservers(this);
  18625. return this._computedViewMatrix;
  18626. };
  18627. Camera.prototype.freezeProjectionMatrix = function (projection) {
  18628. this._doNotComputeProjectionMatrix = true;
  18629. if (projection !== undefined) {
  18630. this._projectionMatrix = projection;
  18631. }
  18632. };
  18633. ;
  18634. Camera.prototype.unfreezeProjectionMatrix = function () {
  18635. this._doNotComputeProjectionMatrix = false;
  18636. };
  18637. ;
  18638. Camera.prototype.getProjectionMatrix = function (force) {
  18639. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  18640. return this._projectionMatrix;
  18641. }
  18642. // Cache
  18643. this._cache.mode = this.mode;
  18644. this._cache.minZ = this.minZ;
  18645. this._cache.maxZ = this.maxZ;
  18646. // Matrix
  18647. this._refreshFrustumPlanes = true;
  18648. var engine = this.getEngine();
  18649. var scene = this.getScene();
  18650. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  18651. this._cache.fov = this.fov;
  18652. this._cache.fovMode = this.fovMode;
  18653. this._cache.aspectRatio = engine.getAspectRatio(this);
  18654. if (this.minZ <= 0) {
  18655. this.minZ = 0.1;
  18656. }
  18657. if (scene.useRightHandedSystem) {
  18658. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  18659. }
  18660. else {
  18661. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  18662. }
  18663. }
  18664. else {
  18665. var halfWidth = engine.getRenderWidth() / 2.0;
  18666. var halfHeight = engine.getRenderHeight() / 2.0;
  18667. if (scene.useRightHandedSystem) {
  18668. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  18669. }
  18670. else {
  18671. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  18672. }
  18673. this._cache.orthoLeft = this.orthoLeft;
  18674. this._cache.orthoRight = this.orthoRight;
  18675. this._cache.orthoBottom = this.orthoBottom;
  18676. this._cache.orthoTop = this.orthoTop;
  18677. this._cache.renderWidth = engine.getRenderWidth();
  18678. this._cache.renderHeight = engine.getRenderHeight();
  18679. }
  18680. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  18681. return this._projectionMatrix;
  18682. };
  18683. Camera.prototype.getTranformationMatrix = function () {
  18684. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  18685. return this._transformMatrix;
  18686. };
  18687. Camera.prototype.updateFrustumPlanes = function () {
  18688. if (!this._refreshFrustumPlanes) {
  18689. return;
  18690. }
  18691. this.getTranformationMatrix();
  18692. if (!this._frustumPlanes) {
  18693. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  18694. }
  18695. else {
  18696. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  18697. }
  18698. this._refreshFrustumPlanes = false;
  18699. };
  18700. Camera.prototype.isInFrustum = function (target) {
  18701. this.updateFrustumPlanes();
  18702. return target.isInFrustum(this._frustumPlanes);
  18703. };
  18704. Camera.prototype.isCompletelyInFrustum = function (target) {
  18705. this.updateFrustumPlanes();
  18706. return target.isCompletelyInFrustum(this._frustumPlanes);
  18707. };
  18708. Camera.prototype.getForwardRay = function (length, transform, origin) {
  18709. if (length === void 0) { length = 100; }
  18710. if (!transform) {
  18711. transform = this.getWorldMatrix();
  18712. }
  18713. if (!origin) {
  18714. origin = this.position;
  18715. }
  18716. var forward = new BABYLON.Vector3(0, 0, 1);
  18717. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  18718. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  18719. return new BABYLON.Ray(origin, direction, length);
  18720. };
  18721. Camera.prototype.dispose = function () {
  18722. // Observables
  18723. this.onViewMatrixChangedObservable.clear();
  18724. this.onProjectionMatrixChangedObservable.clear();
  18725. this.onAfterCheckInputsObservable.clear();
  18726. this.onRestoreStateObservable.clear();
  18727. // Inputs
  18728. if (this.inputs) {
  18729. this.inputs.clear();
  18730. }
  18731. // Animations
  18732. this.getScene().stopAnimation(this);
  18733. // Remove from scene
  18734. this.getScene().removeCamera(this);
  18735. while (this._rigCameras.length > 0) {
  18736. var camera = this._rigCameras.pop();
  18737. if (camera) {
  18738. camera.dispose();
  18739. }
  18740. }
  18741. // Postprocesses
  18742. if (this._rigPostProcess) {
  18743. this._rigPostProcess.dispose(this);
  18744. this._rigPostProcess = null;
  18745. this._postProcesses = [];
  18746. }
  18747. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18748. this._rigPostProcess = null;
  18749. this._postProcesses = [];
  18750. }
  18751. else {
  18752. var i = this._postProcesses.length;
  18753. while (--i >= 0) {
  18754. this._postProcesses[i].dispose(this);
  18755. }
  18756. }
  18757. // Render targets
  18758. var i = this.customRenderTargets.length;
  18759. while (--i >= 0) {
  18760. this.customRenderTargets[i].dispose();
  18761. }
  18762. this.customRenderTargets = [];
  18763. // Active Meshes
  18764. this._activeMeshes.dispose();
  18765. _super.prototype.dispose.call(this);
  18766. };
  18767. Object.defineProperty(Camera.prototype, "leftCamera", {
  18768. // ---- Camera rigs section ----
  18769. get: function () {
  18770. if (this._rigCameras.length < 1) {
  18771. return null;
  18772. }
  18773. return this._rigCameras[0];
  18774. },
  18775. enumerable: true,
  18776. configurable: true
  18777. });
  18778. Object.defineProperty(Camera.prototype, "rightCamera", {
  18779. get: function () {
  18780. if (this._rigCameras.length < 2) {
  18781. return null;
  18782. }
  18783. return this._rigCameras[1];
  18784. },
  18785. enumerable: true,
  18786. configurable: true
  18787. });
  18788. Camera.prototype.getLeftTarget = function () {
  18789. if (this._rigCameras.length < 1) {
  18790. return null;
  18791. }
  18792. return this._rigCameras[0].getTarget();
  18793. };
  18794. Camera.prototype.getRightTarget = function () {
  18795. if (this._rigCameras.length < 2) {
  18796. return null;
  18797. }
  18798. return this._rigCameras[1].getTarget();
  18799. };
  18800. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  18801. if (this.cameraRigMode === mode) {
  18802. return;
  18803. }
  18804. while (this._rigCameras.length > 0) {
  18805. var camera = this._rigCameras.pop();
  18806. if (camera) {
  18807. camera.dispose();
  18808. }
  18809. }
  18810. this.cameraRigMode = mode;
  18811. this._cameraRigParams = {};
  18812. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  18813. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  18814. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  18815. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  18816. // create the rig cameras, unless none
  18817. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18818. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  18819. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  18820. if (leftCamera && rightCamera) {
  18821. this._rigCameras.push(leftCamera);
  18822. this._rigCameras.push(rightCamera);
  18823. }
  18824. }
  18825. switch (this.cameraRigMode) {
  18826. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  18827. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  18828. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  18829. break;
  18830. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  18831. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  18832. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  18833. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  18834. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  18835. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  18836. break;
  18837. case Camera.RIG_MODE_VR:
  18838. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  18839. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  18840. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  18841. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18842. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  18843. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  18844. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  18845. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  18846. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  18847. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18848. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  18849. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  18850. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  18851. if (metrics.compensateDistortion) {
  18852. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  18853. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  18854. }
  18855. break;
  18856. case Camera.RIG_MODE_WEBVR:
  18857. if (rigParams.vrDisplay) {
  18858. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  18859. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  18860. //Left eye
  18861. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  18862. this._rigCameras[0].setCameraRigParameter("left", true);
  18863. //leaving this for future reference
  18864. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  18865. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  18866. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  18867. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  18868. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18869. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  18870. this._rigCameras[0].parent = this;
  18871. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  18872. //Right eye
  18873. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  18874. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  18875. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  18876. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  18877. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  18878. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18879. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  18880. this._rigCameras[1].parent = this;
  18881. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  18882. if (Camera.UseAlternateWebVRRendering) {
  18883. this._rigCameras[1]._skipRendering = true;
  18884. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  18885. }
  18886. }
  18887. break;
  18888. }
  18889. this._cascadePostProcessesToRigCams();
  18890. this.update();
  18891. };
  18892. Camera.prototype._getVRProjectionMatrix = function () {
  18893. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  18894. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  18895. return this._projectionMatrix;
  18896. };
  18897. Camera.prototype._updateCameraRotationMatrix = function () {
  18898. //Here for WebVR
  18899. };
  18900. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  18901. //Here for WebVR
  18902. };
  18903. /**
  18904. * This function MUST be overwritten by the different WebVR cameras available.
  18905. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  18906. */
  18907. Camera.prototype._getWebVRProjectionMatrix = function () {
  18908. return BABYLON.Matrix.Identity();
  18909. };
  18910. /**
  18911. * This function MUST be overwritten by the different WebVR cameras available.
  18912. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  18913. */
  18914. Camera.prototype._getWebVRViewMatrix = function () {
  18915. return BABYLON.Matrix.Identity();
  18916. };
  18917. Camera.prototype.setCameraRigParameter = function (name, value) {
  18918. if (!this._cameraRigParams) {
  18919. this._cameraRigParams = {};
  18920. }
  18921. this._cameraRigParams[name] = value;
  18922. //provisionnally:
  18923. if (name === "interaxialDistance") {
  18924. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  18925. }
  18926. };
  18927. /**
  18928. * needs to be overridden by children so sub has required properties to be copied
  18929. */
  18930. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  18931. return null;
  18932. };
  18933. /**
  18934. * May need to be overridden by children
  18935. */
  18936. Camera.prototype._updateRigCameras = function () {
  18937. for (var i = 0; i < this._rigCameras.length; i++) {
  18938. this._rigCameras[i].minZ = this.minZ;
  18939. this._rigCameras[i].maxZ = this.maxZ;
  18940. this._rigCameras[i].fov = this.fov;
  18941. }
  18942. // only update viewport when ANAGLYPH
  18943. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  18944. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  18945. }
  18946. };
  18947. Camera.prototype._setupInputs = function () {
  18948. };
  18949. Camera.prototype.serialize = function () {
  18950. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  18951. // Type
  18952. serializationObject.type = this.getClassName();
  18953. // Parent
  18954. if (this.parent) {
  18955. serializationObject.parentId = this.parent.id;
  18956. }
  18957. if (this.inputs) {
  18958. this.inputs.serialize(serializationObject);
  18959. }
  18960. // Animations
  18961. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  18962. serializationObject.ranges = this.serializeAnimationRanges();
  18963. return serializationObject;
  18964. };
  18965. Camera.prototype.clone = function (name) {
  18966. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  18967. };
  18968. Camera.prototype.getDirection = function (localAxis) {
  18969. var result = BABYLON.Vector3.Zero();
  18970. this.getDirectionToRef(localAxis, result);
  18971. return result;
  18972. };
  18973. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  18974. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18975. };
  18976. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  18977. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  18978. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  18979. switch (type) {
  18980. case "ArcRotateCamera":
  18981. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  18982. case "DeviceOrientationCamera":
  18983. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  18984. case "FollowCamera":
  18985. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  18986. case "ArcFollowCamera":
  18987. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  18988. case "GamepadCamera":
  18989. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  18990. case "TouchCamera":
  18991. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  18992. case "VirtualJoysticksCamera":
  18993. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  18994. case "WebVRFreeCamera":
  18995. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  18996. case "WebVRGamepadCamera":
  18997. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  18998. case "VRDeviceOrientationFreeCamera":
  18999. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  19000. case "VRDeviceOrientationGamepadCamera":
  19001. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  19002. case "AnaglyphArcRotateCamera":
  19003. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19004. case "AnaglyphFreeCamera":
  19005. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19006. case "AnaglyphGamepadCamera":
  19007. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19008. case "AnaglyphUniversalCamera":
  19009. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19010. case "StereoscopicArcRotateCamera":
  19011. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  19012. case "StereoscopicFreeCamera":
  19013. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  19014. case "StereoscopicGamepadCamera":
  19015. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  19016. case "StereoscopicUniversalCamera":
  19017. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  19018. case "FreeCamera":// Forcing Universal here
  19019. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  19020. default:// Universal Camera is the default value
  19021. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  19022. }
  19023. };
  19024. Camera.prototype.computeWorldMatrix = function () {
  19025. return this.getWorldMatrix();
  19026. };
  19027. Camera.Parse = function (parsedCamera, scene) {
  19028. var type = parsedCamera.type;
  19029. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  19030. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  19031. // Parent
  19032. if (parsedCamera.parentId) {
  19033. camera._waitingParentId = parsedCamera.parentId;
  19034. }
  19035. //If camera has an input manager, let it parse inputs settings
  19036. if (camera.inputs) {
  19037. camera.inputs.parse(parsedCamera);
  19038. camera._setupInputs();
  19039. }
  19040. if (camera.setPosition) {
  19041. camera.position.copyFromFloats(0, 0, 0);
  19042. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  19043. }
  19044. // Target
  19045. if (parsedCamera.target) {
  19046. if (camera.setTarget) {
  19047. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  19048. }
  19049. }
  19050. // Apply 3d rig, when found
  19051. if (parsedCamera.cameraRigMode) {
  19052. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  19053. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  19054. }
  19055. // Animations
  19056. if (parsedCamera.animations) {
  19057. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  19058. var parsedAnimation = parsedCamera.animations[animationIndex];
  19059. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19060. }
  19061. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  19062. }
  19063. if (parsedCamera.autoAnimate) {
  19064. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  19065. }
  19066. return camera;
  19067. };
  19068. // Statics
  19069. Camera._PERSPECTIVE_CAMERA = 0;
  19070. Camera._ORTHOGRAPHIC_CAMERA = 1;
  19071. Camera._FOVMODE_VERTICAL_FIXED = 0;
  19072. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  19073. Camera._RIG_MODE_NONE = 0;
  19074. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  19075. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  19076. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  19077. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  19078. Camera._RIG_MODE_VR = 20;
  19079. Camera._RIG_MODE_WEBVR = 21;
  19080. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  19081. Camera.UseAlternateWebVRRendering = false;
  19082. __decorate([
  19083. BABYLON.serializeAsVector3()
  19084. ], Camera.prototype, "position", void 0);
  19085. __decorate([
  19086. BABYLON.serializeAsVector3()
  19087. ], Camera.prototype, "upVector", void 0);
  19088. __decorate([
  19089. BABYLON.serialize()
  19090. ], Camera.prototype, "orthoLeft", void 0);
  19091. __decorate([
  19092. BABYLON.serialize()
  19093. ], Camera.prototype, "orthoRight", void 0);
  19094. __decorate([
  19095. BABYLON.serialize()
  19096. ], Camera.prototype, "orthoBottom", void 0);
  19097. __decorate([
  19098. BABYLON.serialize()
  19099. ], Camera.prototype, "orthoTop", void 0);
  19100. __decorate([
  19101. BABYLON.serialize()
  19102. ], Camera.prototype, "fov", void 0);
  19103. __decorate([
  19104. BABYLON.serialize()
  19105. ], Camera.prototype, "minZ", void 0);
  19106. __decorate([
  19107. BABYLON.serialize()
  19108. ], Camera.prototype, "maxZ", void 0);
  19109. __decorate([
  19110. BABYLON.serialize()
  19111. ], Camera.prototype, "inertia", void 0);
  19112. __decorate([
  19113. BABYLON.serialize()
  19114. ], Camera.prototype, "mode", void 0);
  19115. __decorate([
  19116. BABYLON.serialize()
  19117. ], Camera.prototype, "layerMask", void 0);
  19118. __decorate([
  19119. BABYLON.serialize()
  19120. ], Camera.prototype, "fovMode", void 0);
  19121. __decorate([
  19122. BABYLON.serialize()
  19123. ], Camera.prototype, "cameraRigMode", void 0);
  19124. __decorate([
  19125. BABYLON.serialize()
  19126. ], Camera.prototype, "interaxialDistance", void 0);
  19127. __decorate([
  19128. BABYLON.serialize()
  19129. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  19130. return Camera;
  19131. }(BABYLON.Node));
  19132. BABYLON.Camera = Camera;
  19133. })(BABYLON || (BABYLON = {}));
  19134. //# sourceMappingURL=babylon.camera.js.map
  19135. var BABYLON;
  19136. (function (BABYLON) {
  19137. var RenderingManager = /** @class */ (function () {
  19138. function RenderingManager(scene) {
  19139. this._renderingGroups = new Array();
  19140. this._autoClearDepthStencil = {};
  19141. this._customOpaqueSortCompareFn = {};
  19142. this._customAlphaTestSortCompareFn = {};
  19143. this._customTransparentSortCompareFn = {};
  19144. this._renderinGroupInfo = null;
  19145. this._scene = scene;
  19146. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  19147. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  19148. }
  19149. }
  19150. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  19151. if (depth === void 0) { depth = true; }
  19152. if (stencil === void 0) { stencil = true; }
  19153. if (this._depthStencilBufferAlreadyCleaned) {
  19154. return;
  19155. }
  19156. this._scene.getEngine().clear(null, false, depth, stencil);
  19157. this._depthStencilBufferAlreadyCleaned = true;
  19158. };
  19159. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  19160. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  19161. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  19162. var info = null;
  19163. if (observable) {
  19164. if (!this._renderinGroupInfo) {
  19165. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  19166. }
  19167. info = this._renderinGroupInfo;
  19168. info.scene = this._scene;
  19169. info.camera = this._scene.activeCamera;
  19170. }
  19171. // Dispatch sprites
  19172. if (renderSprites) {
  19173. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  19174. var manager = this._scene.spriteManagers[index];
  19175. this.dispatchSprites(manager);
  19176. }
  19177. }
  19178. // Render
  19179. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  19180. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  19181. var renderingGroup = this._renderingGroups[index];
  19182. if (!renderingGroup && !observable)
  19183. continue;
  19184. var renderingGroupMask = 0;
  19185. // Fire PRECLEAR stage
  19186. if (observable && info) {
  19187. renderingGroupMask = Math.pow(2, index);
  19188. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  19189. info.renderingGroupId = index;
  19190. observable.notifyObservers(info, renderingGroupMask);
  19191. }
  19192. // Clear depth/stencil if needed
  19193. if (RenderingManager.AUTOCLEAR) {
  19194. var autoClear = this._autoClearDepthStencil[index];
  19195. if (autoClear && autoClear.autoClear) {
  19196. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  19197. }
  19198. }
  19199. if (observable && info) {
  19200. // Fire PREOPAQUE stage
  19201. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  19202. observable.notifyObservers(info, renderingGroupMask);
  19203. // Fire PRETRANSPARENT stage
  19204. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  19205. observable.notifyObservers(info, renderingGroupMask);
  19206. }
  19207. if (renderingGroup)
  19208. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  19209. // Fire POSTTRANSPARENT stage
  19210. if (observable && info) {
  19211. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  19212. observable.notifyObservers(info, renderingGroupMask);
  19213. }
  19214. }
  19215. };
  19216. RenderingManager.prototype.reset = function () {
  19217. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  19218. var renderingGroup = this._renderingGroups[index];
  19219. if (renderingGroup) {
  19220. renderingGroup.prepare();
  19221. }
  19222. }
  19223. };
  19224. RenderingManager.prototype.dispose = function () {
  19225. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  19226. var renderingGroup = this._renderingGroups[index];
  19227. if (renderingGroup) {
  19228. renderingGroup.dispose();
  19229. }
  19230. }
  19231. this._renderingGroups.length = 0;
  19232. };
  19233. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  19234. if (this._renderingGroups[renderingGroupId] === undefined) {
  19235. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  19236. }
  19237. };
  19238. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  19239. var renderingGroupId = spriteManager.renderingGroupId || 0;
  19240. this._prepareRenderingGroup(renderingGroupId);
  19241. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  19242. };
  19243. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  19244. var renderingGroupId = particleSystem.renderingGroupId || 0;
  19245. this._prepareRenderingGroup(renderingGroupId);
  19246. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  19247. };
  19248. /**
  19249. * @param subMesh The submesh to dispatch
  19250. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  19251. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  19252. */
  19253. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  19254. if (mesh === undefined) {
  19255. mesh = subMesh.getMesh();
  19256. }
  19257. var renderingGroupId = mesh.renderingGroupId || 0;
  19258. this._prepareRenderingGroup(renderingGroupId);
  19259. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  19260. };
  19261. /**
  19262. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  19263. * This allowed control for front to back rendering or reversly depending of the special needs.
  19264. *
  19265. * @param renderingGroupId The rendering group id corresponding to its index
  19266. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  19267. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  19268. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  19269. */
  19270. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  19271. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  19272. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  19273. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  19274. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  19275. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  19276. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  19277. if (this._renderingGroups[renderingGroupId]) {
  19278. var group = this._renderingGroups[renderingGroupId];
  19279. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  19280. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  19281. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  19282. }
  19283. };
  19284. /**
  19285. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  19286. *
  19287. * @param renderingGroupId The rendering group id corresponding to its index
  19288. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  19289. * @param depth Automatically clears depth between groups if true and autoClear is true.
  19290. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  19291. */
  19292. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  19293. if (depth === void 0) { depth = true; }
  19294. if (stencil === void 0) { stencil = true; }
  19295. this._autoClearDepthStencil[renderingGroupId] = {
  19296. autoClear: autoClearDepthStencil,
  19297. depth: depth,
  19298. stencil: stencil
  19299. };
  19300. };
  19301. /**
  19302. * The max id used for rendering groups (not included)
  19303. */
  19304. RenderingManager.MAX_RENDERINGGROUPS = 4;
  19305. /**
  19306. * The min id used for rendering groups (included)
  19307. */
  19308. RenderingManager.MIN_RENDERINGGROUPS = 0;
  19309. /**
  19310. * Used to globally prevent autoclearing scenes.
  19311. */
  19312. RenderingManager.AUTOCLEAR = true;
  19313. return RenderingManager;
  19314. }());
  19315. BABYLON.RenderingManager = RenderingManager;
  19316. })(BABYLON || (BABYLON = {}));
  19317. //# sourceMappingURL=babylon.renderingManager.js.map
  19318. var BABYLON;
  19319. (function (BABYLON) {
  19320. var RenderingGroup = /** @class */ (function () {
  19321. /**
  19322. * Creates a new rendering group.
  19323. * @param index The rendering group index
  19324. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  19325. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  19326. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  19327. */
  19328. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  19329. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  19330. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  19331. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  19332. this.index = index;
  19333. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  19334. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  19335. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  19336. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  19337. this._particleSystems = new BABYLON.SmartArray(256);
  19338. this._spriteManagers = new BABYLON.SmartArray(256);
  19339. this._edgesRenderers = new BABYLON.SmartArray(16);
  19340. this._scene = scene;
  19341. this.opaqueSortCompareFn = opaqueSortCompareFn;
  19342. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  19343. this.transparentSortCompareFn = transparentSortCompareFn;
  19344. }
  19345. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  19346. /**
  19347. * Set the opaque sort comparison function.
  19348. * If null the sub meshes will be render in the order they were created
  19349. */
  19350. set: function (value) {
  19351. this._opaqueSortCompareFn = value;
  19352. if (value) {
  19353. this._renderOpaque = this.renderOpaqueSorted;
  19354. }
  19355. else {
  19356. this._renderOpaque = RenderingGroup.renderUnsorted;
  19357. }
  19358. },
  19359. enumerable: true,
  19360. configurable: true
  19361. });
  19362. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  19363. /**
  19364. * Set the alpha test sort comparison function.
  19365. * If null the sub meshes will be render in the order they were created
  19366. */
  19367. set: function (value) {
  19368. this._alphaTestSortCompareFn = value;
  19369. if (value) {
  19370. this._renderAlphaTest = this.renderAlphaTestSorted;
  19371. }
  19372. else {
  19373. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  19374. }
  19375. },
  19376. enumerable: true,
  19377. configurable: true
  19378. });
  19379. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  19380. /**
  19381. * Set the transparent sort comparison function.
  19382. * If null the sub meshes will be render in the order they were created
  19383. */
  19384. set: function (value) {
  19385. if (value) {
  19386. this._transparentSortCompareFn = value;
  19387. }
  19388. else {
  19389. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  19390. }
  19391. this._renderTransparent = this.renderTransparentSorted;
  19392. },
  19393. enumerable: true,
  19394. configurable: true
  19395. });
  19396. /**
  19397. * Render all the sub meshes contained in the group.
  19398. * @param customRenderFunction Used to override the default render behaviour of the group.
  19399. * @returns true if rendered some submeshes.
  19400. */
  19401. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  19402. if (customRenderFunction) {
  19403. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  19404. return;
  19405. }
  19406. var engine = this._scene.getEngine();
  19407. // Depth only
  19408. if (this._depthOnlySubMeshes.length !== 0) {
  19409. engine.setColorWrite(false);
  19410. this._renderAlphaTest(this._depthOnlySubMeshes);
  19411. engine.setColorWrite(true);
  19412. }
  19413. // Opaque
  19414. if (this._opaqueSubMeshes.length !== 0) {
  19415. this._renderOpaque(this._opaqueSubMeshes);
  19416. }
  19417. // Alpha test
  19418. if (this._alphaTestSubMeshes.length !== 0) {
  19419. this._renderAlphaTest(this._alphaTestSubMeshes);
  19420. }
  19421. var stencilState = engine.getStencilBuffer();
  19422. engine.setStencilBuffer(false);
  19423. // Sprites
  19424. if (renderSprites) {
  19425. this._renderSprites();
  19426. }
  19427. // Particles
  19428. if (renderParticles) {
  19429. this._renderParticles(activeMeshes);
  19430. }
  19431. if (this.onBeforeTransparentRendering) {
  19432. this.onBeforeTransparentRendering();
  19433. }
  19434. // Transparent
  19435. if (this._transparentSubMeshes.length !== 0) {
  19436. this._renderTransparent(this._transparentSubMeshes);
  19437. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  19438. }
  19439. // Set back stencil to false in case it changes before the edge renderer.
  19440. engine.setStencilBuffer(false);
  19441. // Edges
  19442. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  19443. this._edgesRenderers.data[edgesRendererIndex].render();
  19444. }
  19445. // Restore Stencil state.
  19446. engine.setStencilBuffer(stencilState);
  19447. };
  19448. /**
  19449. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  19450. * @param subMeshes The submeshes to render
  19451. */
  19452. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  19453. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  19454. };
  19455. /**
  19456. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  19457. * @param subMeshes The submeshes to render
  19458. */
  19459. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  19460. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  19461. };
  19462. /**
  19463. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  19464. * @param subMeshes The submeshes to render
  19465. */
  19466. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  19467. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  19468. };
  19469. /**
  19470. * Renders the submeshes in a specified order.
  19471. * @param subMeshes The submeshes to sort before render
  19472. * @param sortCompareFn The comparison function use to sort
  19473. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  19474. * @param transparent Specifies to activate blending if true
  19475. */
  19476. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  19477. var subIndex = 0;
  19478. var subMesh;
  19479. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  19480. for (; subIndex < subMeshes.length; subIndex++) {
  19481. subMesh = subMeshes.data[subIndex];
  19482. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  19483. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  19484. }
  19485. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  19486. if (sortCompareFn) {
  19487. sortedArray.sort(sortCompareFn);
  19488. }
  19489. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  19490. subMesh = sortedArray[subIndex];
  19491. if (transparent) {
  19492. var material = subMesh.getMaterial();
  19493. if (material && material.needDepthPrePass) {
  19494. var engine = material.getScene().getEngine();
  19495. engine.setColorWrite(false);
  19496. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  19497. subMesh.render(false);
  19498. engine.setColorWrite(true);
  19499. }
  19500. }
  19501. subMesh.render(transparent);
  19502. }
  19503. };
  19504. /**
  19505. * Renders the submeshes in the order they were dispatched (no sort applied).
  19506. * @param subMeshes The submeshes to render
  19507. */
  19508. RenderingGroup.renderUnsorted = function (subMeshes) {
  19509. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  19510. var submesh = subMeshes.data[subIndex];
  19511. submesh.render(false);
  19512. }
  19513. };
  19514. /**
  19515. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19516. * are rendered back to front if in the same alpha index.
  19517. *
  19518. * @param a The first submesh
  19519. * @param b The second submesh
  19520. * @returns The result of the comparison
  19521. */
  19522. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  19523. // Alpha index first
  19524. if (a._alphaIndex > b._alphaIndex) {
  19525. return 1;
  19526. }
  19527. if (a._alphaIndex < b._alphaIndex) {
  19528. return -1;
  19529. }
  19530. // Then distance to camera
  19531. return RenderingGroup.backToFrontSortCompare(a, b);
  19532. };
  19533. /**
  19534. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19535. * are rendered back to front.
  19536. *
  19537. * @param a The first submesh
  19538. * @param b The second submesh
  19539. * @returns The result of the comparison
  19540. */
  19541. RenderingGroup.backToFrontSortCompare = function (a, b) {
  19542. // Then distance to camera
  19543. if (a._distanceToCamera < b._distanceToCamera) {
  19544. return 1;
  19545. }
  19546. if (a._distanceToCamera > b._distanceToCamera) {
  19547. return -1;
  19548. }
  19549. return 0;
  19550. };
  19551. /**
  19552. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19553. * are rendered front to back (prevent overdraw).
  19554. *
  19555. * @param a The first submesh
  19556. * @param b The second submesh
  19557. * @returns The result of the comparison
  19558. */
  19559. RenderingGroup.frontToBackSortCompare = function (a, b) {
  19560. // Then distance to camera
  19561. if (a._distanceToCamera < b._distanceToCamera) {
  19562. return -1;
  19563. }
  19564. if (a._distanceToCamera > b._distanceToCamera) {
  19565. return 1;
  19566. }
  19567. return 0;
  19568. };
  19569. /**
  19570. * Resets the different lists of submeshes to prepare a new frame.
  19571. */
  19572. RenderingGroup.prototype.prepare = function () {
  19573. this._opaqueSubMeshes.reset();
  19574. this._transparentSubMeshes.reset();
  19575. this._alphaTestSubMeshes.reset();
  19576. this._depthOnlySubMeshes.reset();
  19577. this._particleSystems.reset();
  19578. this._spriteManagers.reset();
  19579. this._edgesRenderers.reset();
  19580. };
  19581. RenderingGroup.prototype.dispose = function () {
  19582. this._opaqueSubMeshes.dispose();
  19583. this._transparentSubMeshes.dispose();
  19584. this._alphaTestSubMeshes.dispose();
  19585. this._depthOnlySubMeshes.dispose();
  19586. this._particleSystems.dispose();
  19587. this._spriteManagers.dispose();
  19588. this._edgesRenderers.dispose();
  19589. };
  19590. /**
  19591. * Inserts the submesh in its correct queue depending on its material.
  19592. * @param subMesh The submesh to dispatch
  19593. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  19594. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  19595. */
  19596. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  19597. // Get mesh and materials if not provided
  19598. if (mesh === undefined) {
  19599. mesh = subMesh.getMesh();
  19600. }
  19601. if (material === undefined) {
  19602. material = subMesh.getMaterial();
  19603. }
  19604. if (material === null || material === undefined) {
  19605. return;
  19606. }
  19607. if (material.needAlphaBlendingForMesh(mesh)) {
  19608. this._transparentSubMeshes.push(subMesh);
  19609. }
  19610. else if (material.needAlphaTesting()) {
  19611. if (material.needDepthPrePass) {
  19612. this._depthOnlySubMeshes.push(subMesh);
  19613. }
  19614. this._alphaTestSubMeshes.push(subMesh);
  19615. }
  19616. else {
  19617. if (material.needDepthPrePass) {
  19618. this._depthOnlySubMeshes.push(subMesh);
  19619. }
  19620. this._opaqueSubMeshes.push(subMesh); // Opaque
  19621. }
  19622. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  19623. this._edgesRenderers.push(mesh._edgesRenderer);
  19624. }
  19625. };
  19626. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  19627. this._spriteManagers.push(spriteManager);
  19628. };
  19629. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  19630. this._particleSystems.push(particleSystem);
  19631. };
  19632. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  19633. if (this._particleSystems.length === 0) {
  19634. return;
  19635. }
  19636. // Particles
  19637. var activeCamera = this._scene.activeCamera;
  19638. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  19639. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  19640. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  19641. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  19642. continue;
  19643. }
  19644. var emitter = particleSystem.emitter;
  19645. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  19646. this._scene._activeParticles.addCount(particleSystem.render(), false);
  19647. }
  19648. }
  19649. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  19650. };
  19651. RenderingGroup.prototype._renderSprites = function () {
  19652. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  19653. return;
  19654. }
  19655. // Sprites
  19656. var activeCamera = this._scene.activeCamera;
  19657. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  19658. for (var id = 0; id < this._spriteManagers.length; id++) {
  19659. var spriteManager = this._spriteManagers.data[id];
  19660. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  19661. spriteManager.render();
  19662. }
  19663. }
  19664. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  19665. };
  19666. return RenderingGroup;
  19667. }());
  19668. BABYLON.RenderingGroup = RenderingGroup;
  19669. })(BABYLON || (BABYLON = {}));
  19670. //# sourceMappingURL=babylon.renderingGroup.js.map
  19671. var BABYLON;
  19672. (function (BABYLON) {
  19673. var ClickInfo = /** @class */ (function () {
  19674. function ClickInfo() {
  19675. this._singleClick = false;
  19676. this._doubleClick = false;
  19677. this._hasSwiped = false;
  19678. this._ignore = false;
  19679. }
  19680. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  19681. get: function () {
  19682. return this._singleClick;
  19683. },
  19684. set: function (b) {
  19685. this._singleClick = b;
  19686. },
  19687. enumerable: true,
  19688. configurable: true
  19689. });
  19690. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  19691. get: function () {
  19692. return this._doubleClick;
  19693. },
  19694. set: function (b) {
  19695. this._doubleClick = b;
  19696. },
  19697. enumerable: true,
  19698. configurable: true
  19699. });
  19700. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  19701. get: function () {
  19702. return this._hasSwiped;
  19703. },
  19704. set: function (b) {
  19705. this._hasSwiped = b;
  19706. },
  19707. enumerable: true,
  19708. configurable: true
  19709. });
  19710. Object.defineProperty(ClickInfo.prototype, "ignore", {
  19711. get: function () {
  19712. return this._ignore;
  19713. },
  19714. set: function (b) {
  19715. this._ignore = b;
  19716. },
  19717. enumerable: true,
  19718. configurable: true
  19719. });
  19720. return ClickInfo;
  19721. }());
  19722. /**
  19723. * This class is used by the onRenderingGroupObservable
  19724. */
  19725. var RenderingGroupInfo = /** @class */ (function () {
  19726. function RenderingGroupInfo() {
  19727. }
  19728. /**
  19729. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  19730. * This stage will be fired no matter what
  19731. */
  19732. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  19733. /**
  19734. * Called before opaque object are rendered.
  19735. * This stage will be fired only if there's 3D Opaque content to render
  19736. */
  19737. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  19738. /**
  19739. * Called after the opaque objects are rendered and before the transparent ones
  19740. * This stage will be fired only if there's 3D transparent content to render
  19741. */
  19742. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  19743. /**
  19744. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  19745. * This stage will be fired no matter what
  19746. */
  19747. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  19748. return RenderingGroupInfo;
  19749. }());
  19750. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  19751. /**
  19752. * Represents a scene to be rendered by the engine.
  19753. * @see http://doc.babylonjs.com/page.php?p=21911
  19754. */
  19755. var Scene = /** @class */ (function () {
  19756. /**
  19757. * @constructor
  19758. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  19759. */
  19760. function Scene(engine) {
  19761. // Members
  19762. this.autoClear = true;
  19763. this.autoClearDepthAndStencil = true;
  19764. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  19765. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  19766. this.forceWireframe = false;
  19767. this._forcePointsCloud = false;
  19768. this.forceShowBoundingBoxes = false;
  19769. this.animationsEnabled = true;
  19770. this.useConstantAnimationDeltaTime = false;
  19771. this.constantlyUpdateMeshUnderPointer = false;
  19772. this.hoverCursor = "pointer";
  19773. this.defaultCursor = "";
  19774. /**
  19775. * This is used to call preventDefault() on pointer down
  19776. * in order to block unwanted artifacts like system double clicks
  19777. */
  19778. this.preventDefaultOnPointerDown = true;
  19779. // Metadata
  19780. this.metadata = null;
  19781. /**
  19782. * An event triggered when the scene is disposed.
  19783. * @type {BABYLON.Observable}
  19784. */
  19785. this.onDisposeObservable = new BABYLON.Observable();
  19786. /**
  19787. * An event triggered before rendering the scene (right after animations and physics)
  19788. * @type {BABYLON.Observable}
  19789. */
  19790. this.onBeforeRenderObservable = new BABYLON.Observable();
  19791. /**
  19792. * An event triggered after rendering the scene
  19793. * @type {BABYLON.Observable}
  19794. */
  19795. this.onAfterRenderObservable = new BABYLON.Observable();
  19796. /**
  19797. * An event triggered before animating the scene
  19798. * @type {BABYLON.Observable}
  19799. */
  19800. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  19801. /**
  19802. * An event triggered after animations processing
  19803. * @type {BABYLON.Observable}
  19804. */
  19805. this.onAfterAnimationsObservable = new BABYLON.Observable();
  19806. /**
  19807. * An event triggered before draw calls are ready to be sent
  19808. * @type {BABYLON.Observable}
  19809. */
  19810. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  19811. /**
  19812. * An event triggered after draw calls have been sent
  19813. * @type {BABYLON.Observable}
  19814. */
  19815. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  19816. /**
  19817. * An event triggered when physic simulation is about to be run
  19818. * @type {BABYLON.Observable}
  19819. */
  19820. this.onBeforePhysicsObservable = new BABYLON.Observable();
  19821. /**
  19822. * An event triggered when physic simulation has been done
  19823. * @type {BABYLON.Observable}
  19824. */
  19825. this.onAfterPhysicsObservable = new BABYLON.Observable();
  19826. /**
  19827. * An event triggered when the scene is ready
  19828. * @type {BABYLON.Observable}
  19829. */
  19830. this.onReadyObservable = new BABYLON.Observable();
  19831. /**
  19832. * An event triggered before rendering a camera
  19833. * @type {BABYLON.Observable}
  19834. */
  19835. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  19836. /**
  19837. * An event triggered after rendering a camera
  19838. * @type {BABYLON.Observable}
  19839. */
  19840. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  19841. /**
  19842. * An event triggered when active meshes evaluation is about to start
  19843. * @type {BABYLON.Observable}
  19844. */
  19845. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  19846. /**
  19847. * An event triggered when active meshes evaluation is done
  19848. * @type {BABYLON.Observable}
  19849. */
  19850. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  19851. /**
  19852. * An event triggered when particles rendering is about to start
  19853. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  19854. * @type {BABYLON.Observable}
  19855. */
  19856. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  19857. /**
  19858. * An event triggered when particles rendering is done
  19859. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  19860. * @type {BABYLON.Observable}
  19861. */
  19862. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  19863. /**
  19864. * An event triggered when sprites rendering is about to start
  19865. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  19866. * @type {BABYLON.Observable}
  19867. */
  19868. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  19869. /**
  19870. * An event triggered when sprites rendering is done
  19871. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  19872. * @type {BABYLON.Observable}
  19873. */
  19874. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  19875. /**
  19876. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  19877. * @type {BABYLON.Observable}
  19878. */
  19879. this.onDataLoadedObservable = new BABYLON.Observable();
  19880. /**
  19881. * An event triggered when a camera is created
  19882. * @type {BABYLON.Observable}
  19883. */
  19884. this.onNewCameraAddedObservable = new BABYLON.Observable();
  19885. /**
  19886. * An event triggered when a camera is removed
  19887. * @type {BABYLON.Observable}
  19888. */
  19889. this.onCameraRemovedObservable = new BABYLON.Observable();
  19890. /**
  19891. * An event triggered when a light is created
  19892. * @type {BABYLON.Observable}
  19893. */
  19894. this.onNewLightAddedObservable = new BABYLON.Observable();
  19895. /**
  19896. * An event triggered when a light is removed
  19897. * @type {BABYLON.Observable}
  19898. */
  19899. this.onLightRemovedObservable = new BABYLON.Observable();
  19900. /**
  19901. * An event triggered when a geometry is created
  19902. * @type {BABYLON.Observable}
  19903. */
  19904. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  19905. /**
  19906. * An event triggered when a geometry is removed
  19907. * @type {BABYLON.Observable}
  19908. */
  19909. this.onGeometryRemovedObservable = new BABYLON.Observable();
  19910. /**
  19911. * An event triggered when a transform node is created
  19912. * @type {BABYLON.Observable}
  19913. */
  19914. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  19915. /**
  19916. * An event triggered when a transform node is removed
  19917. * @type {BABYLON.Observable}
  19918. */
  19919. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  19920. /**
  19921. * An event triggered when a mesh is created
  19922. * @type {BABYLON.Observable}
  19923. */
  19924. this.onNewMeshAddedObservable = new BABYLON.Observable();
  19925. /**
  19926. * An event triggered when a mesh is removed
  19927. * @type {BABYLON.Observable}
  19928. */
  19929. this.onMeshRemovedObservable = new BABYLON.Observable();
  19930. /**
  19931. * An event triggered when render targets are about to be rendered
  19932. * Can happen multiple times per frame.
  19933. * @type {BABYLON.Observable}
  19934. */
  19935. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  19936. /**
  19937. * An event triggered when render targets were rendered.
  19938. * Can happen multiple times per frame.
  19939. * @type {BABYLON.Observable}
  19940. */
  19941. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  19942. /**
  19943. * An event triggered before calculating deterministic simulation step
  19944. * @type {BABYLON.Observable}
  19945. */
  19946. this.onBeforeStepObservable = new BABYLON.Observable();
  19947. /**
  19948. * An event triggered after calculating deterministic simulation step
  19949. * @type {BABYLON.Observable}
  19950. */
  19951. this.onAfterStepObservable = new BABYLON.Observable();
  19952. /**
  19953. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  19954. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  19955. * 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)
  19956. */
  19957. this.onRenderingGroupObservable = new BABYLON.Observable();
  19958. // Animations
  19959. this.animations = [];
  19960. /**
  19961. * 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).
  19962. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  19963. */
  19964. this.onPrePointerObservable = new BABYLON.Observable();
  19965. /**
  19966. * Observable event triggered each time an input event is received from the rendering canvas
  19967. */
  19968. this.onPointerObservable = new BABYLON.Observable();
  19969. this._meshPickProceed = false;
  19970. this._currentPickResult = null;
  19971. this._previousPickResult = null;
  19972. this._totalPointersPressed = 0;
  19973. this._doubleClickOccured = false;
  19974. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  19975. this.cameraToUseForPointers = null;
  19976. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  19977. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  19978. this._startingPointerTime = 0;
  19979. this._previousStartingPointerTime = 0;
  19980. // Deterministic lockstep
  19981. this._timeAccumulator = 0;
  19982. this._currentStepId = 0;
  19983. this._currentInternalStep = 0;
  19984. // Keyboard
  19985. /**
  19986. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  19987. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  19988. */
  19989. this.onPreKeyboardObservable = new BABYLON.Observable();
  19990. /**
  19991. * Observable event triggered each time an keyboard event is received from the hosting window
  19992. */
  19993. this.onKeyboardObservable = new BABYLON.Observable();
  19994. // Coordinate system
  19995. /**
  19996. * use right-handed coordinate system on this scene.
  19997. * @type {boolean}
  19998. */
  19999. this._useRightHandedSystem = false;
  20000. // Fog
  20001. this._fogEnabled = true;
  20002. this._fogMode = Scene.FOGMODE_NONE;
  20003. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  20004. this.fogDensity = 0.1;
  20005. this.fogStart = 0;
  20006. this.fogEnd = 1000.0;
  20007. // Lights
  20008. /**
  20009. * is shadow enabled on this scene.
  20010. * @type {boolean}
  20011. */
  20012. this._shadowsEnabled = true;
  20013. /**
  20014. * is light enabled on this scene.
  20015. * @type {boolean}
  20016. */
  20017. this._lightsEnabled = true;
  20018. /**
  20019. * All of the lights added to this scene.
  20020. * @see BABYLON.Light
  20021. * @type {BABYLON.Light[]}
  20022. */
  20023. this.lights = new Array();
  20024. // Cameras
  20025. /** All of the cameras added to this scene. */
  20026. this.cameras = new Array();
  20027. /** All of the active cameras added to this scene. */
  20028. this.activeCameras = new Array();
  20029. // Meshes
  20030. /**
  20031. * All of the tranform nodes added to this scene.
  20032. * @see BABYLON.TransformNode
  20033. * @type {BABYLON.TransformNode[]}
  20034. */
  20035. this.transformNodes = new Array();
  20036. /**
  20037. * All of the (abstract) meshes added to this scene.
  20038. * @see BABYLON.AbstractMesh
  20039. * @type {BABYLON.AbstractMesh[]}
  20040. */
  20041. this.meshes = new Array();
  20042. /**
  20043. * All of the animation groups added to this scene.
  20044. * @see BABYLON.AnimationGroup
  20045. * @type {BABYLON.AnimationGroup[]}
  20046. */
  20047. this.animationGroups = new Array();
  20048. // Geometries
  20049. this._geometries = new Array();
  20050. this.materials = new Array();
  20051. this.multiMaterials = new Array();
  20052. // Textures
  20053. this._texturesEnabled = true;
  20054. this.textures = new Array();
  20055. // Particles
  20056. this.particlesEnabled = true;
  20057. this.particleSystems = new Array();
  20058. // Sprites
  20059. this.spritesEnabled = true;
  20060. this.spriteManagers = new Array();
  20061. // Layers
  20062. this.layers = new Array();
  20063. this.highlightLayers = new Array();
  20064. // Skeletons
  20065. this._skeletonsEnabled = true;
  20066. this.skeletons = new Array();
  20067. // Morph targets
  20068. this.morphTargetManagers = new Array();
  20069. // Lens flares
  20070. this.lensFlaresEnabled = true;
  20071. this.lensFlareSystems = new Array();
  20072. // Collisions
  20073. this.collisionsEnabled = true;
  20074. /** Defines the gravity applied to this scene */
  20075. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  20076. // Postprocesses
  20077. this.postProcesses = new Array();
  20078. this.postProcessesEnabled = true;
  20079. // Customs render targets
  20080. this.renderTargetsEnabled = true;
  20081. this.dumpNextRenderTargets = false;
  20082. this.customRenderTargets = new Array();
  20083. // Imported meshes
  20084. this.importedMeshesFiles = new Array();
  20085. // Probes
  20086. this.probesEnabled = true;
  20087. this.reflectionProbes = new Array();
  20088. this._actionManagers = new Array();
  20089. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  20090. // Procedural textures
  20091. this.proceduralTexturesEnabled = true;
  20092. this._proceduralTextures = new Array();
  20093. this.soundTracks = new Array();
  20094. this._audioEnabled = true;
  20095. this._headphone = false;
  20096. // Performance counters
  20097. this._totalVertices = new BABYLON.PerfCounter();
  20098. this._activeIndices = new BABYLON.PerfCounter();
  20099. this._activeParticles = new BABYLON.PerfCounter();
  20100. this._activeBones = new BABYLON.PerfCounter();
  20101. this._animationTime = 0;
  20102. this.animationTimeScale = 1;
  20103. this._renderId = 0;
  20104. this._executeWhenReadyTimeoutId = -1;
  20105. this._intermediateRendering = false;
  20106. this._viewUpdateFlag = -1;
  20107. this._projectionUpdateFlag = -1;
  20108. this._alternateViewUpdateFlag = -1;
  20109. this._alternateProjectionUpdateFlag = -1;
  20110. this._toBeDisposed = new BABYLON.SmartArray(256);
  20111. this._activeRequests = new Array();
  20112. this._pendingData = new Array();
  20113. this._isDisposed = false;
  20114. this.dispatchAllSubMeshesOfActiveMeshes = false;
  20115. this._activeMeshes = new BABYLON.SmartArray(256);
  20116. this._processedMaterials = new BABYLON.SmartArray(256);
  20117. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  20118. this._activeParticleSystems = new BABYLON.SmartArray(256);
  20119. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  20120. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  20121. this._activeAnimatables = new Array();
  20122. this._transformMatrix = BABYLON.Matrix.Zero();
  20123. this._useAlternateCameraConfiguration = false;
  20124. this._alternateRendering = false;
  20125. this.requireLightSorting = false;
  20126. this._activeMeshesFrozen = false;
  20127. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  20128. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  20129. this._engine.scenes.push(this);
  20130. this._uid = null;
  20131. this._renderingManager = new BABYLON.RenderingManager(this);
  20132. this.postProcessManager = new BABYLON.PostProcessManager(this);
  20133. if (BABYLON.OutlineRenderer) {
  20134. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  20135. }
  20136. if (BABYLON.Tools.IsWindowObjectExist()) {
  20137. this.attachControl();
  20138. }
  20139. //simplification queue
  20140. if (BABYLON.SimplificationQueue) {
  20141. this.simplificationQueue = new BABYLON.SimplificationQueue();
  20142. }
  20143. //collision coordinator initialization. For now legacy per default.
  20144. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  20145. // Uniform Buffer
  20146. this._createUbo();
  20147. // Default Image processing definition.
  20148. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  20149. }
  20150. Object.defineProperty(Scene, "FOGMODE_NONE", {
  20151. /** The fog is deactivated */
  20152. get: function () {
  20153. return Scene._FOGMODE_NONE;
  20154. },
  20155. enumerable: true,
  20156. configurable: true
  20157. });
  20158. Object.defineProperty(Scene, "FOGMODE_EXP", {
  20159. /** The fog density is following an exponential function */
  20160. get: function () {
  20161. return Scene._FOGMODE_EXP;
  20162. },
  20163. enumerable: true,
  20164. configurable: true
  20165. });
  20166. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  20167. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  20168. get: function () {
  20169. return Scene._FOGMODE_EXP2;
  20170. },
  20171. enumerable: true,
  20172. configurable: true
  20173. });
  20174. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  20175. /** The fog density is following a linear function. */
  20176. get: function () {
  20177. return Scene._FOGMODE_LINEAR;
  20178. },
  20179. enumerable: true,
  20180. configurable: true
  20181. });
  20182. Object.defineProperty(Scene.prototype, "environmentTexture", {
  20183. /**
  20184. * Texture used in all pbr material as the reflection texture.
  20185. * As in the majority of the scene they are the same (exception for multi room and so on),
  20186. * this is easier to reference from here than from all the materials.
  20187. */
  20188. get: function () {
  20189. return this._environmentTexture;
  20190. },
  20191. /**
  20192. * Texture used in all pbr material as the reflection texture.
  20193. * As in the majority of the scene they are the same (exception for multi room and so on),
  20194. * this is easier to set here than in all the materials.
  20195. */
  20196. set: function (value) {
  20197. if (this._environmentTexture === value) {
  20198. return;
  20199. }
  20200. this._environmentTexture = value;
  20201. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20202. },
  20203. enumerable: true,
  20204. configurable: true
  20205. });
  20206. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  20207. /**
  20208. * Default image processing configuration used either in the rendering
  20209. * Forward main pass or through the imageProcessingPostProcess if present.
  20210. * As in the majority of the scene they are the same (exception for multi camera),
  20211. * this is easier to reference from here than from all the materials and post process.
  20212. *
  20213. * No setter as we it is a shared configuration, you can set the values instead.
  20214. */
  20215. get: function () {
  20216. return this._imageProcessingConfiguration;
  20217. },
  20218. enumerable: true,
  20219. configurable: true
  20220. });
  20221. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  20222. get: function () {
  20223. return this._forcePointsCloud;
  20224. },
  20225. set: function (value) {
  20226. if (this._forcePointsCloud === value) {
  20227. return;
  20228. }
  20229. this._forcePointsCloud = value;
  20230. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  20231. },
  20232. enumerable: true,
  20233. configurable: true
  20234. });
  20235. Object.defineProperty(Scene.prototype, "onDispose", {
  20236. /** A function to be executed when this scene is disposed. */
  20237. set: function (callback) {
  20238. if (this._onDisposeObserver) {
  20239. this.onDisposeObservable.remove(this._onDisposeObserver);
  20240. }
  20241. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  20242. },
  20243. enumerable: true,
  20244. configurable: true
  20245. });
  20246. Object.defineProperty(Scene.prototype, "beforeRender", {
  20247. /** A function to be executed before rendering this scene */
  20248. set: function (callback) {
  20249. if (this._onBeforeRenderObserver) {
  20250. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  20251. }
  20252. if (callback) {
  20253. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  20254. }
  20255. },
  20256. enumerable: true,
  20257. configurable: true
  20258. });
  20259. Object.defineProperty(Scene.prototype, "afterRender", {
  20260. /** A function to be executed after rendering this scene */
  20261. set: function (callback) {
  20262. if (this._onAfterRenderObserver) {
  20263. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  20264. }
  20265. if (callback) {
  20266. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  20267. }
  20268. },
  20269. enumerable: true,
  20270. configurable: true
  20271. });
  20272. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  20273. set: function (callback) {
  20274. if (this._onBeforeCameraRenderObserver) {
  20275. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  20276. }
  20277. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  20278. },
  20279. enumerable: true,
  20280. configurable: true
  20281. });
  20282. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  20283. set: function (callback) {
  20284. if (this._onAfterCameraRenderObserver) {
  20285. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  20286. }
  20287. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  20288. },
  20289. enumerable: true,
  20290. configurable: true
  20291. });
  20292. Object.defineProperty(Scene.prototype, "gamepadManager", {
  20293. get: function () {
  20294. if (!this._gamepadManager) {
  20295. this._gamepadManager = new BABYLON.GamepadManager(this);
  20296. }
  20297. return this._gamepadManager;
  20298. },
  20299. enumerable: true,
  20300. configurable: true
  20301. });
  20302. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  20303. get: function () {
  20304. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  20305. },
  20306. enumerable: true,
  20307. configurable: true
  20308. });
  20309. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  20310. get: function () {
  20311. return this._useRightHandedSystem;
  20312. },
  20313. set: function (value) {
  20314. if (this._useRightHandedSystem === value) {
  20315. return;
  20316. }
  20317. this._useRightHandedSystem = value;
  20318. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  20319. },
  20320. enumerable: true,
  20321. configurable: true
  20322. });
  20323. Scene.prototype.setStepId = function (newStepId) {
  20324. this._currentStepId = newStepId;
  20325. };
  20326. ;
  20327. Scene.prototype.getStepId = function () {
  20328. return this._currentStepId;
  20329. };
  20330. ;
  20331. Scene.prototype.getInternalStep = function () {
  20332. return this._currentInternalStep;
  20333. };
  20334. ;
  20335. Object.defineProperty(Scene.prototype, "fogEnabled", {
  20336. get: function () {
  20337. return this._fogEnabled;
  20338. },
  20339. /**
  20340. * is fog enabled on this scene.
  20341. */
  20342. set: function (value) {
  20343. if (this._fogEnabled === value) {
  20344. return;
  20345. }
  20346. this._fogEnabled = value;
  20347. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  20348. },
  20349. enumerable: true,
  20350. configurable: true
  20351. });
  20352. Object.defineProperty(Scene.prototype, "fogMode", {
  20353. get: function () {
  20354. return this._fogMode;
  20355. },
  20356. set: function (value) {
  20357. if (this._fogMode === value) {
  20358. return;
  20359. }
  20360. this._fogMode = value;
  20361. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  20362. },
  20363. enumerable: true,
  20364. configurable: true
  20365. });
  20366. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  20367. get: function () {
  20368. return this._shadowsEnabled;
  20369. },
  20370. set: function (value) {
  20371. if (this._shadowsEnabled === value) {
  20372. return;
  20373. }
  20374. this._shadowsEnabled = value;
  20375. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  20376. },
  20377. enumerable: true,
  20378. configurable: true
  20379. });
  20380. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  20381. get: function () {
  20382. return this._lightsEnabled;
  20383. },
  20384. set: function (value) {
  20385. if (this._lightsEnabled === value) {
  20386. return;
  20387. }
  20388. this._lightsEnabled = value;
  20389. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  20390. },
  20391. enumerable: true,
  20392. configurable: true
  20393. });
  20394. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  20395. /** The default material used on meshes when no material is affected */
  20396. get: function () {
  20397. if (!this._defaultMaterial) {
  20398. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  20399. }
  20400. return this._defaultMaterial;
  20401. },
  20402. /** The default material used on meshes when no material is affected */
  20403. set: function (value) {
  20404. this._defaultMaterial = value;
  20405. },
  20406. enumerable: true,
  20407. configurable: true
  20408. });
  20409. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  20410. get: function () {
  20411. return this._texturesEnabled;
  20412. },
  20413. set: function (value) {
  20414. if (this._texturesEnabled === value) {
  20415. return;
  20416. }
  20417. this._texturesEnabled = value;
  20418. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20419. },
  20420. enumerable: true,
  20421. configurable: true
  20422. });
  20423. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  20424. get: function () {
  20425. return this._skeletonsEnabled;
  20426. },
  20427. set: function (value) {
  20428. if (this._skeletonsEnabled === value) {
  20429. return;
  20430. }
  20431. this._skeletonsEnabled = value;
  20432. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  20433. },
  20434. enumerable: true,
  20435. configurable: true
  20436. });
  20437. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  20438. get: function () {
  20439. if (!this._postProcessRenderPipelineManager) {
  20440. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  20441. }
  20442. return this._postProcessRenderPipelineManager;
  20443. },
  20444. enumerable: true,
  20445. configurable: true
  20446. });
  20447. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  20448. get: function () {
  20449. if (!this._mainSoundTrack) {
  20450. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  20451. }
  20452. return this._mainSoundTrack;
  20453. },
  20454. enumerable: true,
  20455. configurable: true
  20456. });
  20457. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  20458. get: function () {
  20459. return this._alternateRendering;
  20460. },
  20461. enumerable: true,
  20462. configurable: true
  20463. });
  20464. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  20465. get: function () {
  20466. return this._frustumPlanes;
  20467. },
  20468. enumerable: true,
  20469. configurable: true
  20470. });
  20471. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  20472. /**
  20473. * Gets the current geometry buffer associated to the scene.
  20474. */
  20475. get: function () {
  20476. return this._geometryBufferRenderer;
  20477. },
  20478. /**
  20479. * Sets the current geometry buffer for the scene.
  20480. */
  20481. set: function (geometryBufferRenderer) {
  20482. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  20483. this._geometryBufferRenderer = geometryBufferRenderer;
  20484. }
  20485. },
  20486. enumerable: true,
  20487. configurable: true
  20488. });
  20489. Object.defineProperty(Scene.prototype, "debugLayer", {
  20490. // Properties
  20491. get: function () {
  20492. if (!this._debugLayer) {
  20493. this._debugLayer = new BABYLON.DebugLayer(this);
  20494. }
  20495. return this._debugLayer;
  20496. },
  20497. enumerable: true,
  20498. configurable: true
  20499. });
  20500. Object.defineProperty(Scene.prototype, "workerCollisions", {
  20501. get: function () {
  20502. return this._workerCollisions;
  20503. },
  20504. set: function (enabled) {
  20505. if (!BABYLON.CollisionCoordinatorLegacy) {
  20506. return;
  20507. }
  20508. enabled = (enabled && !!Worker);
  20509. this._workerCollisions = enabled;
  20510. if (this.collisionCoordinator) {
  20511. this.collisionCoordinator.destroy();
  20512. }
  20513. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  20514. this.collisionCoordinator.init(this);
  20515. },
  20516. enumerable: true,
  20517. configurable: true
  20518. });
  20519. Object.defineProperty(Scene.prototype, "selectionOctree", {
  20520. get: function () {
  20521. return this._selectionOctree;
  20522. },
  20523. enumerable: true,
  20524. configurable: true
  20525. });
  20526. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  20527. /**
  20528. * The mesh that is currently under the pointer.
  20529. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  20530. */
  20531. get: function () {
  20532. return this._pointerOverMesh;
  20533. },
  20534. enumerable: true,
  20535. configurable: true
  20536. });
  20537. Object.defineProperty(Scene.prototype, "pointerX", {
  20538. /**
  20539. * Current on-screen X position of the pointer
  20540. * @return {number} X position of the pointer
  20541. */
  20542. get: function () {
  20543. return this._pointerX;
  20544. },
  20545. enumerable: true,
  20546. configurable: true
  20547. });
  20548. Object.defineProperty(Scene.prototype, "pointerY", {
  20549. /**
  20550. * Current on-screen Y position of the pointer
  20551. * @return {number} Y position of the pointer
  20552. */
  20553. get: function () {
  20554. return this._pointerY;
  20555. },
  20556. enumerable: true,
  20557. configurable: true
  20558. });
  20559. Scene.prototype.getCachedMaterial = function () {
  20560. return this._cachedMaterial;
  20561. };
  20562. Scene.prototype.getCachedEffect = function () {
  20563. return this._cachedEffect;
  20564. };
  20565. Scene.prototype.getCachedVisibility = function () {
  20566. return this._cachedVisibility;
  20567. };
  20568. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  20569. if (visibility === void 0) { visibility = 1; }
  20570. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  20571. };
  20572. Scene.prototype.getBoundingBoxRenderer = function () {
  20573. if (!this._boundingBoxRenderer) {
  20574. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  20575. }
  20576. return this._boundingBoxRenderer;
  20577. };
  20578. Scene.prototype.getOutlineRenderer = function () {
  20579. return this._outlineRenderer;
  20580. };
  20581. Scene.prototype.getEngine = function () {
  20582. return this._engine;
  20583. };
  20584. Scene.prototype.getTotalVertices = function () {
  20585. return this._totalVertices.current;
  20586. };
  20587. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  20588. get: function () {
  20589. return this._totalVertices;
  20590. },
  20591. enumerable: true,
  20592. configurable: true
  20593. });
  20594. Scene.prototype.getActiveIndices = function () {
  20595. return this._activeIndices.current;
  20596. };
  20597. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  20598. get: function () {
  20599. return this._activeIndices;
  20600. },
  20601. enumerable: true,
  20602. configurable: true
  20603. });
  20604. Scene.prototype.getActiveParticles = function () {
  20605. return this._activeParticles.current;
  20606. };
  20607. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  20608. get: function () {
  20609. return this._activeParticles;
  20610. },
  20611. enumerable: true,
  20612. configurable: true
  20613. });
  20614. Scene.prototype.getActiveBones = function () {
  20615. return this._activeBones.current;
  20616. };
  20617. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  20618. get: function () {
  20619. return this._activeBones;
  20620. },
  20621. enumerable: true,
  20622. configurable: true
  20623. });
  20624. // Stats
  20625. Scene.prototype.getInterFramePerfCounter = function () {
  20626. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20627. return 0;
  20628. };
  20629. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  20630. get: function () {
  20631. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20632. return null;
  20633. },
  20634. enumerable: true,
  20635. configurable: true
  20636. });
  20637. Scene.prototype.getLastFrameDuration = function () {
  20638. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  20639. return 0;
  20640. };
  20641. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  20642. get: function () {
  20643. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20644. return null;
  20645. },
  20646. enumerable: true,
  20647. configurable: true
  20648. });
  20649. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  20650. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  20651. return 0;
  20652. };
  20653. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  20654. get: function () {
  20655. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20656. return null;
  20657. },
  20658. enumerable: true,
  20659. configurable: true
  20660. });
  20661. Scene.prototype.getActiveMeshes = function () {
  20662. return this._activeMeshes;
  20663. };
  20664. Scene.prototype.getRenderTargetsDuration = function () {
  20665. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  20666. return 0;
  20667. };
  20668. Scene.prototype.getRenderDuration = function () {
  20669. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  20670. return 0;
  20671. };
  20672. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  20673. get: function () {
  20674. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20675. return null;
  20676. },
  20677. enumerable: true,
  20678. configurable: true
  20679. });
  20680. Scene.prototype.getParticlesDuration = function () {
  20681. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  20682. return 0;
  20683. };
  20684. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  20685. get: function () {
  20686. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20687. return null;
  20688. },
  20689. enumerable: true,
  20690. configurable: true
  20691. });
  20692. Scene.prototype.getSpritesDuration = function () {
  20693. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  20694. return 0;
  20695. };
  20696. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  20697. get: function () {
  20698. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  20699. return null;
  20700. },
  20701. enumerable: true,
  20702. configurable: true
  20703. });
  20704. Scene.prototype.getAnimationRatio = function () {
  20705. return this._animationRatio;
  20706. };
  20707. Scene.prototype.getRenderId = function () {
  20708. return this._renderId;
  20709. };
  20710. Scene.prototype.incrementRenderId = function () {
  20711. this._renderId++;
  20712. };
  20713. Scene.prototype._updatePointerPosition = function (evt) {
  20714. var canvasRect = this._engine.getRenderingCanvasClientRect();
  20715. if (!canvasRect) {
  20716. return;
  20717. }
  20718. this._pointerX = evt.clientX - canvasRect.left;
  20719. this._pointerY = evt.clientY - canvasRect.top;
  20720. this._unTranslatedPointerX = this._pointerX;
  20721. this._unTranslatedPointerY = this._pointerY;
  20722. };
  20723. Scene.prototype._createUbo = function () {
  20724. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  20725. this._sceneUbo.addUniform("viewProjection", 16);
  20726. this._sceneUbo.addUniform("view", 16);
  20727. };
  20728. Scene.prototype._createAlternateUbo = function () {
  20729. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  20730. this._alternateSceneUbo.addUniform("viewProjection", 16);
  20731. this._alternateSceneUbo.addUniform("view", 16);
  20732. };
  20733. // Pointers handling
  20734. /**
  20735. * Use this method to simulate a pointer move on a mesh
  20736. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20737. */
  20738. Scene.prototype.simulatePointerMove = function (pickResult) {
  20739. var evt = new PointerEvent("pointermove");
  20740. return this._processPointerMove(pickResult, evt);
  20741. };
  20742. Scene.prototype._processPointerMove = function (pickResult, evt) {
  20743. var canvas = this._engine.getRenderingCanvas();
  20744. if (!canvas) {
  20745. return this;
  20746. }
  20747. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  20748. this.setPointerOverSprite(null);
  20749. this.setPointerOverMesh(pickResult.pickedMesh);
  20750. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  20751. if (this._pointerOverMesh.actionManager.hoverCursor) {
  20752. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  20753. }
  20754. else {
  20755. canvas.style.cursor = this.hoverCursor;
  20756. }
  20757. }
  20758. else {
  20759. canvas.style.cursor = this.defaultCursor;
  20760. }
  20761. }
  20762. else {
  20763. this.setPointerOverMesh(null);
  20764. // Sprites
  20765. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  20766. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  20767. this.setPointerOverSprite(pickResult.pickedSprite);
  20768. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  20769. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  20770. }
  20771. else {
  20772. canvas.style.cursor = this.hoverCursor;
  20773. }
  20774. }
  20775. else {
  20776. this.setPointerOverSprite(null);
  20777. // Restore pointer
  20778. canvas.style.cursor = this.defaultCursor;
  20779. }
  20780. }
  20781. if (pickResult) {
  20782. if (this.onPointerMove) {
  20783. this.onPointerMove(evt, pickResult);
  20784. }
  20785. if (this.onPointerObservable.hasObservers()) {
  20786. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  20787. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20788. this.onPointerObservable.notifyObservers(pi, type);
  20789. }
  20790. }
  20791. return this;
  20792. };
  20793. /**
  20794. * Use this method to simulate a pointer down on a mesh
  20795. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20796. */
  20797. Scene.prototype.simulatePointerDown = function (pickResult) {
  20798. var evt = new PointerEvent("pointerdown");
  20799. return this._processPointerDown(pickResult, evt);
  20800. };
  20801. Scene.prototype._processPointerDown = function (pickResult, evt) {
  20802. var _this = this;
  20803. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  20804. this._pickedDownMesh = pickResult.pickedMesh;
  20805. var actionManager = pickResult.pickedMesh.actionManager;
  20806. if (actionManager) {
  20807. if (actionManager.hasPickTriggers) {
  20808. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20809. switch (evt.button) {
  20810. case 0:
  20811. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20812. break;
  20813. case 1:
  20814. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20815. break;
  20816. case 2:
  20817. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20818. break;
  20819. }
  20820. }
  20821. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  20822. window.setTimeout(function () {
  20823. 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);
  20824. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  20825. if (_this._totalPointersPressed !== 0 &&
  20826. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  20827. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  20828. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  20829. _this._startingPointerTime = 0;
  20830. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20831. }
  20832. }
  20833. }, Scene.LongPressDelay);
  20834. }
  20835. }
  20836. }
  20837. if (pickResult) {
  20838. if (this.onPointerDown) {
  20839. this.onPointerDown(evt, pickResult);
  20840. }
  20841. if (this.onPointerObservable.hasObservers()) {
  20842. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  20843. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20844. this.onPointerObservable.notifyObservers(pi, type);
  20845. }
  20846. }
  20847. return this;
  20848. };
  20849. /**
  20850. * Use this method to simulate a pointer up on a mesh
  20851. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20852. */
  20853. Scene.prototype.simulatePointerUp = function (pickResult) {
  20854. var evt = new PointerEvent("pointerup");
  20855. var clickInfo = new ClickInfo();
  20856. clickInfo.singleClick = true;
  20857. clickInfo.ignore = true;
  20858. return this._processPointerUp(pickResult, evt, clickInfo);
  20859. };
  20860. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  20861. if (pickResult && pickResult && pickResult.pickedMesh) {
  20862. this._pickedUpMesh = pickResult.pickedMesh;
  20863. if (this._pickedDownMesh === this._pickedUpMesh) {
  20864. if (this.onPointerPick) {
  20865. this.onPointerPick(evt, pickResult);
  20866. }
  20867. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  20868. var type = BABYLON.PointerEventTypes.POINTERPICK;
  20869. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20870. this.onPointerObservable.notifyObservers(pi, type);
  20871. }
  20872. }
  20873. if (pickResult.pickedMesh.actionManager) {
  20874. if (clickInfo.ignore) {
  20875. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20876. }
  20877. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  20878. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20879. }
  20880. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20881. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20882. }
  20883. }
  20884. }
  20885. if (this._pickedDownMesh &&
  20886. this._pickedDownMesh.actionManager &&
  20887. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  20888. this._pickedDownMesh !== this._pickedUpMesh) {
  20889. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  20890. }
  20891. if (this.onPointerUp) {
  20892. this.onPointerUp(evt, pickResult);
  20893. }
  20894. if (this.onPointerObservable.hasObservers()) {
  20895. if (!clickInfo.ignore) {
  20896. if (!clickInfo.hasSwiped) {
  20897. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  20898. var type = BABYLON.PointerEventTypes.POINTERTAP;
  20899. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20900. this.onPointerObservable.notifyObservers(pi, type);
  20901. }
  20902. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  20903. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  20904. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20905. this.onPointerObservable.notifyObservers(pi, type);
  20906. }
  20907. }
  20908. }
  20909. else {
  20910. var type = BABYLON.PointerEventTypes.POINTERUP;
  20911. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20912. this.onPointerObservable.notifyObservers(pi, type);
  20913. }
  20914. }
  20915. return this;
  20916. };
  20917. /**
  20918. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  20919. * @param attachUp defines if you want to attach events to pointerup
  20920. * @param attachDown defines if you want to attach events to pointerdown
  20921. * @param attachMove defines if you want to attach events to pointermove
  20922. */
  20923. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  20924. var _this = this;
  20925. if (attachUp === void 0) { attachUp = true; }
  20926. if (attachDown === void 0) { attachDown = true; }
  20927. if (attachMove === void 0) { attachMove = true; }
  20928. this._initActionManager = function (act, clickInfo) {
  20929. if (!_this._meshPickProceed) {
  20930. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  20931. _this._currentPickResult = pickResult;
  20932. if (pickResult) {
  20933. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  20934. }
  20935. _this._meshPickProceed = true;
  20936. }
  20937. return act;
  20938. };
  20939. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  20940. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  20941. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  20942. btn !== _this._previousButtonPressed) {
  20943. _this._doubleClickOccured = false;
  20944. clickInfo.singleClick = true;
  20945. clickInfo.ignore = false;
  20946. cb(clickInfo, _this._currentPickResult);
  20947. }
  20948. };
  20949. this._initClickEvent = function (obs1, obs2, evt, cb) {
  20950. var clickInfo = new ClickInfo();
  20951. _this._currentPickResult = null;
  20952. var act = null;
  20953. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  20954. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  20955. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  20956. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  20957. act = _this._initActionManager(act, clickInfo);
  20958. if (act)
  20959. checkPicking = act.hasPickTriggers;
  20960. }
  20961. if (checkPicking) {
  20962. var btn = evt.button;
  20963. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  20964. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  20965. if (!clickInfo.hasSwiped) {
  20966. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  20967. if (!checkSingleClickImmediately) {
  20968. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  20969. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  20970. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20971. act = _this._initActionManager(act, clickInfo);
  20972. if (act)
  20973. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  20974. }
  20975. }
  20976. if (checkSingleClickImmediately) {
  20977. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  20978. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  20979. btn !== _this._previousButtonPressed) {
  20980. clickInfo.singleClick = true;
  20981. cb(clickInfo, _this._currentPickResult);
  20982. }
  20983. }
  20984. else {
  20985. // wait that no double click has been raised during the double click delay
  20986. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20987. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  20988. }
  20989. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  20990. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  20991. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20992. act = _this._initActionManager(act, clickInfo);
  20993. if (act)
  20994. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  20995. }
  20996. if (checkDoubleClick) {
  20997. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  20998. if (btn === _this._previousButtonPressed &&
  20999. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  21000. !_this._doubleClickOccured) {
  21001. // pointer has not moved for 2 clicks, it's a double click
  21002. if (!clickInfo.hasSwiped &&
  21003. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  21004. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  21005. _this._previousStartingPointerTime = 0;
  21006. _this._doubleClickOccured = true;
  21007. clickInfo.doubleClick = true;
  21008. clickInfo.ignore = false;
  21009. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  21010. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  21011. }
  21012. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  21013. cb(clickInfo, _this._currentPickResult);
  21014. }
  21015. else {
  21016. _this._doubleClickOccured = false;
  21017. _this._previousStartingPointerTime = _this._startingPointerTime;
  21018. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  21019. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  21020. _this._previousButtonPressed = btn;
  21021. if (Scene.ExclusiveDoubleClickMode) {
  21022. if (_this._previousDelayedSimpleClickTimeout) {
  21023. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  21024. }
  21025. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  21026. cb(clickInfo, _this._previousPickResult);
  21027. }
  21028. else {
  21029. cb(clickInfo, _this._currentPickResult);
  21030. }
  21031. }
  21032. }
  21033. else {
  21034. _this._doubleClickOccured = false;
  21035. _this._previousStartingPointerTime = _this._startingPointerTime;
  21036. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  21037. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  21038. _this._previousButtonPressed = btn;
  21039. }
  21040. }
  21041. }
  21042. }
  21043. clickInfo.ignore = true;
  21044. cb(clickInfo, _this._currentPickResult);
  21045. };
  21046. this._spritePredicate = function (sprite) {
  21047. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  21048. };
  21049. this._onPointerMove = function (evt) {
  21050. _this._updatePointerPosition(evt);
  21051. // PreObservable support
  21052. if (_this.onPrePointerObservable.hasObservers()) {
  21053. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  21054. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  21055. _this.onPrePointerObservable.notifyObservers(pi, type);
  21056. if (pi.skipOnPointerObservable) {
  21057. return;
  21058. }
  21059. }
  21060. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  21061. return;
  21062. }
  21063. if (!_this.pointerMovePredicate) {
  21064. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  21065. }
  21066. // Meshes
  21067. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  21068. _this._processPointerMove(pickResult, evt);
  21069. };
  21070. this._onPointerDown = function (evt) {
  21071. _this._totalPointersPressed++;
  21072. _this._pickedDownMesh = null;
  21073. _this._meshPickProceed = false;
  21074. _this._updatePointerPosition(evt);
  21075. if (_this.preventDefaultOnPointerDown && canvas) {
  21076. evt.preventDefault();
  21077. canvas.focus();
  21078. }
  21079. // PreObservable support
  21080. if (_this.onPrePointerObservable.hasObservers()) {
  21081. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  21082. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  21083. _this.onPrePointerObservable.notifyObservers(pi, type);
  21084. if (pi.skipOnPointerObservable) {
  21085. return;
  21086. }
  21087. }
  21088. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  21089. return;
  21090. }
  21091. _this._startingPointerPosition.x = _this._pointerX;
  21092. _this._startingPointerPosition.y = _this._pointerY;
  21093. _this._startingPointerTime = new Date().getTime();
  21094. if (!_this.pointerDownPredicate) {
  21095. _this.pointerDownPredicate = function (mesh) {
  21096. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  21097. };
  21098. }
  21099. // Meshes
  21100. _this._pickedDownMesh = null;
  21101. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  21102. _this._processPointerDown(pickResult, evt);
  21103. // Sprites
  21104. _this._pickedDownSprite = null;
  21105. if (_this.spriteManagers.length > 0) {
  21106. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  21107. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  21108. if (pickResult.pickedSprite.actionManager) {
  21109. _this._pickedDownSprite = pickResult.pickedSprite;
  21110. switch (evt.button) {
  21111. case 0:
  21112. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  21113. break;
  21114. case 1:
  21115. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  21116. break;
  21117. case 2:
  21118. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  21119. break;
  21120. }
  21121. if (pickResult.pickedSprite.actionManager) {
  21122. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  21123. }
  21124. }
  21125. }
  21126. }
  21127. };
  21128. this._onPointerUp = function (evt) {
  21129. if (_this._totalPointersPressed === 0) {
  21130. return; // So we need to test it the pointer down was pressed before.
  21131. }
  21132. _this._totalPointersPressed--;
  21133. _this._pickedUpMesh = null;
  21134. _this._meshPickProceed = false;
  21135. _this._updatePointerPosition(evt);
  21136. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  21137. // PreObservable support
  21138. if (_this.onPrePointerObservable.hasObservers()) {
  21139. if (!clickInfo.ignore) {
  21140. if (!clickInfo.hasSwiped) {
  21141. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  21142. var type = BABYLON.PointerEventTypes.POINTERTAP;
  21143. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  21144. _this.onPrePointerObservable.notifyObservers(pi, type);
  21145. if (pi.skipOnPointerObservable) {
  21146. return;
  21147. }
  21148. }
  21149. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  21150. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  21151. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  21152. _this.onPrePointerObservable.notifyObservers(pi, type);
  21153. if (pi.skipOnPointerObservable) {
  21154. return;
  21155. }
  21156. }
  21157. }
  21158. }
  21159. else {
  21160. var type = BABYLON.PointerEventTypes.POINTERUP;
  21161. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  21162. _this.onPrePointerObservable.notifyObservers(pi, type);
  21163. if (pi.skipOnPointerObservable) {
  21164. return;
  21165. }
  21166. }
  21167. }
  21168. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  21169. return;
  21170. }
  21171. if (!_this.pointerUpPredicate) {
  21172. _this.pointerUpPredicate = function (mesh) {
  21173. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  21174. };
  21175. }
  21176. // Meshes
  21177. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  21178. _this._initActionManager(null, clickInfo);
  21179. }
  21180. if (!pickResult) {
  21181. pickResult = _this._currentPickResult;
  21182. }
  21183. _this._processPointerUp(pickResult, evt, clickInfo);
  21184. // Sprites
  21185. if (_this.spriteManagers.length > 0) {
  21186. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  21187. if (spritePickResult) {
  21188. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  21189. if (spritePickResult.pickedSprite.actionManager) {
  21190. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  21191. if (spritePickResult.pickedSprite.actionManager) {
  21192. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  21193. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  21194. }
  21195. }
  21196. }
  21197. }
  21198. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  21199. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  21200. }
  21201. }
  21202. }
  21203. _this._previousPickResult = _this._currentPickResult;
  21204. });
  21205. };
  21206. this._onKeyDown = function (evt) {
  21207. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  21208. if (_this.onPreKeyboardObservable.hasObservers()) {
  21209. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  21210. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  21211. if (pi.skipOnPointerObservable) {
  21212. return;
  21213. }
  21214. }
  21215. if (_this.onKeyboardObservable.hasObservers()) {
  21216. var pi = new BABYLON.KeyboardInfo(type, evt);
  21217. _this.onKeyboardObservable.notifyObservers(pi, type);
  21218. }
  21219. if (_this.actionManager) {
  21220. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  21221. }
  21222. };
  21223. this._onKeyUp = function (evt) {
  21224. var type = BABYLON.KeyboardEventTypes.KEYUP;
  21225. if (_this.onPreKeyboardObservable.hasObservers()) {
  21226. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  21227. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  21228. if (pi.skipOnPointerObservable) {
  21229. return;
  21230. }
  21231. }
  21232. if (_this.onKeyboardObservable.hasObservers()) {
  21233. var pi = new BABYLON.KeyboardInfo(type, evt);
  21234. _this.onKeyboardObservable.notifyObservers(pi, type);
  21235. }
  21236. if (_this.actionManager) {
  21237. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  21238. }
  21239. };
  21240. var engine = this.getEngine();
  21241. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  21242. if (!canvas) {
  21243. return;
  21244. }
  21245. canvas.addEventListener("keydown", _this._onKeyDown, false);
  21246. canvas.addEventListener("keyup", _this._onKeyUp, false);
  21247. });
  21248. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  21249. if (!canvas) {
  21250. return;
  21251. }
  21252. canvas.removeEventListener("keydown", _this._onKeyDown);
  21253. canvas.removeEventListener("keyup", _this._onKeyUp);
  21254. });
  21255. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  21256. var canvas = this._engine.getRenderingCanvas();
  21257. if (!canvas) {
  21258. return;
  21259. }
  21260. if (attachMove) {
  21261. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  21262. // Wheel
  21263. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  21264. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  21265. }
  21266. if (attachDown) {
  21267. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  21268. }
  21269. if (attachUp) {
  21270. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  21271. }
  21272. canvas.tabIndex = 1;
  21273. };
  21274. Scene.prototype.detachControl = function () {
  21275. var engine = this.getEngine();
  21276. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  21277. var canvas = engine.getRenderingCanvas();
  21278. if (!canvas) {
  21279. return;
  21280. }
  21281. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  21282. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  21283. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  21284. if (this._onCanvasBlurObserver) {
  21285. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  21286. }
  21287. if (this._onCanvasFocusObserver) {
  21288. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  21289. }
  21290. // Wheel
  21291. canvas.removeEventListener('mousewheel', this._onPointerMove);
  21292. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  21293. // Keyboard
  21294. canvas.removeEventListener("keydown", this._onKeyDown);
  21295. canvas.removeEventListener("keyup", this._onKeyUp);
  21296. // Observables
  21297. this.onKeyboardObservable.clear();
  21298. this.onPreKeyboardObservable.clear();
  21299. this.onPointerObservable.clear();
  21300. this.onPrePointerObservable.clear();
  21301. };
  21302. /**
  21303. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  21304. * Delay loaded resources are not taking in account
  21305. * @return true if all required resources are ready
  21306. */
  21307. Scene.prototype.isReady = function () {
  21308. if (this._isDisposed) {
  21309. return false;
  21310. }
  21311. if (this._pendingData.length > 0) {
  21312. return false;
  21313. }
  21314. var index;
  21315. var engine = this.getEngine();
  21316. // Geometries
  21317. for (index = 0; index < this._geometries.length; index++) {
  21318. var geometry = this._geometries[index];
  21319. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  21320. return false;
  21321. }
  21322. }
  21323. // Meshes
  21324. for (index = 0; index < this.meshes.length; index++) {
  21325. var mesh = this.meshes[index];
  21326. if (!mesh.isEnabled()) {
  21327. continue;
  21328. }
  21329. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  21330. continue;
  21331. }
  21332. if (!mesh.isReady()) {
  21333. return false;
  21334. }
  21335. // Highlight layers
  21336. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  21337. for (var _i = 0, _a = this.highlightLayers; _i < _a.length; _i++) {
  21338. var layer = _a[_i];
  21339. if (!layer.hasMesh(mesh)) {
  21340. continue;
  21341. }
  21342. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  21343. var subMesh = _c[_b];
  21344. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  21345. return false;
  21346. }
  21347. }
  21348. }
  21349. }
  21350. return true;
  21351. };
  21352. Scene.prototype.resetCachedMaterial = function () {
  21353. this._cachedMaterial = null;
  21354. this._cachedEffect = null;
  21355. this._cachedVisibility = null;
  21356. };
  21357. Scene.prototype.registerBeforeRender = function (func) {
  21358. this.onBeforeRenderObservable.add(func);
  21359. };
  21360. Scene.prototype.unregisterBeforeRender = function (func) {
  21361. this.onBeforeRenderObservable.removeCallback(func);
  21362. };
  21363. Scene.prototype.registerAfterRender = function (func) {
  21364. this.onAfterRenderObservable.add(func);
  21365. };
  21366. Scene.prototype.unregisterAfterRender = function (func) {
  21367. this.onAfterRenderObservable.removeCallback(func);
  21368. };
  21369. Scene.prototype._executeOnceBeforeRender = function (func) {
  21370. var _this = this;
  21371. var execFunc = function () {
  21372. func();
  21373. setTimeout(function () {
  21374. _this.unregisterBeforeRender(execFunc);
  21375. });
  21376. };
  21377. this.registerBeforeRender(execFunc);
  21378. };
  21379. /**
  21380. * The provided function will run before render once and will be disposed afterwards.
  21381. * A timeout delay can be provided so that the function will be executed in N ms.
  21382. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  21383. * @param func The function to be executed.
  21384. * @param timeout optional delay in ms
  21385. */
  21386. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  21387. var _this = this;
  21388. if (timeout !== undefined) {
  21389. setTimeout(function () {
  21390. _this._executeOnceBeforeRender(func);
  21391. }, timeout);
  21392. }
  21393. else {
  21394. this._executeOnceBeforeRender(func);
  21395. }
  21396. };
  21397. Scene.prototype._addPendingData = function (data) {
  21398. this._pendingData.push(data);
  21399. };
  21400. Scene.prototype._removePendingData = function (data) {
  21401. var wasLoading = this.isLoading;
  21402. var index = this._pendingData.indexOf(data);
  21403. if (index !== -1) {
  21404. this._pendingData.splice(index, 1);
  21405. }
  21406. if (wasLoading && !this.isLoading) {
  21407. this.onDataLoadedObservable.notifyObservers(this);
  21408. }
  21409. };
  21410. Scene.prototype.getWaitingItemsCount = function () {
  21411. return this._pendingData.length;
  21412. };
  21413. Object.defineProperty(Scene.prototype, "isLoading", {
  21414. get: function () {
  21415. return this._pendingData.length > 0;
  21416. },
  21417. enumerable: true,
  21418. configurable: true
  21419. });
  21420. /**
  21421. * Registers a function to be executed when the scene is ready.
  21422. * @param {Function} func - the function to be executed.
  21423. */
  21424. Scene.prototype.executeWhenReady = function (func) {
  21425. var _this = this;
  21426. this.onReadyObservable.add(func);
  21427. if (this._executeWhenReadyTimeoutId !== -1) {
  21428. return;
  21429. }
  21430. this._executeWhenReadyTimeoutId = setTimeout(function () {
  21431. _this._checkIsReady();
  21432. }, 150);
  21433. };
  21434. Scene.prototype._checkIsReady = function () {
  21435. var _this = this;
  21436. if (this.isReady()) {
  21437. this.onReadyObservable.notifyObservers(this);
  21438. this.onReadyObservable.clear();
  21439. this._executeWhenReadyTimeoutId = -1;
  21440. return;
  21441. }
  21442. this._executeWhenReadyTimeoutId = setTimeout(function () {
  21443. _this._checkIsReady();
  21444. }, 150);
  21445. };
  21446. // Animations
  21447. /**
  21448. * Will start the animation sequence of a given target
  21449. * @param target - the target
  21450. * @param {number} from - from which frame should animation start
  21451. * @param {number} to - till which frame should animation run.
  21452. * @param {boolean} [loop] - should the animation loop
  21453. * @param {number} [speedRatio] - the speed in which to run the animation
  21454. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  21455. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  21456. * Returns {BABYLON.Animatable} the animatable object created for this animation
  21457. * See BABYLON.Animatable
  21458. */
  21459. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  21460. if (speedRatio === void 0) { speedRatio = 1.0; }
  21461. if (from > to && speedRatio > 0) {
  21462. speedRatio *= -1;
  21463. }
  21464. this.stopAnimation(target);
  21465. if (!animatable) {
  21466. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  21467. }
  21468. // Local animations
  21469. if (target.animations) {
  21470. animatable.appendAnimations(target, target.animations);
  21471. }
  21472. // Children animations
  21473. if (target.getAnimatables) {
  21474. var animatables = target.getAnimatables();
  21475. for (var index = 0; index < animatables.length; index++) {
  21476. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  21477. }
  21478. }
  21479. animatable.reset();
  21480. return animatable;
  21481. };
  21482. /**
  21483. * Begin a new animation on a given node
  21484. * @param {BABYLON.Node} node defines the root node where the animation will take place
  21485. * @param {BABYLON.Animation[]} defines the list of animations to start
  21486. * @param {number} from defines the initial value
  21487. * @param {number} to defines the final value
  21488. * @param {boolean} loop defines if you want animation to loop (off by default)
  21489. * @param {number} speedRatio defines the speed ratio to apply to all animations
  21490. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  21491. * @returns the list of created animatables
  21492. */
  21493. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  21494. if (speedRatio === undefined) {
  21495. speedRatio = 1.0;
  21496. }
  21497. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  21498. return animatable;
  21499. };
  21500. /**
  21501. * Begin a new animation on a given node and its hierarchy
  21502. * @param {BABYLON.Node} node defines the root node where the animation will take place
  21503. * @param {boolean} directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used.
  21504. * @param {BABYLON.Animation[]} defines the list of animations to start
  21505. * @param {number} from defines the initial value
  21506. * @param {number} to defines the final value
  21507. * @param {boolean} loop defines if you want animation to loop (off by default)
  21508. * @param {number} speedRatio defines the speed ratio to apply to all animations
  21509. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  21510. * @returns the list of animatables created for all nodes
  21511. */
  21512. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  21513. var children = target.getDescendants(directDescendantsOnly);
  21514. var result = [];
  21515. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  21516. var child = children_1[_i];
  21517. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  21518. }
  21519. return result;
  21520. };
  21521. Scene.prototype.getAnimatableByTarget = function (target) {
  21522. for (var index = 0; index < this._activeAnimatables.length; index++) {
  21523. if (this._activeAnimatables[index].target === target) {
  21524. return this._activeAnimatables[index];
  21525. }
  21526. }
  21527. return null;
  21528. };
  21529. Object.defineProperty(Scene.prototype, "animatables", {
  21530. get: function () {
  21531. return this._activeAnimatables;
  21532. },
  21533. enumerable: true,
  21534. configurable: true
  21535. });
  21536. /**
  21537. * Will stop the animation of the given target
  21538. * @param target - the target
  21539. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  21540. * @see beginAnimation
  21541. */
  21542. Scene.prototype.stopAnimation = function (target, animationName) {
  21543. var animatable = this.getAnimatableByTarget(target);
  21544. if (animatable) {
  21545. animatable.stop(animationName);
  21546. }
  21547. };
  21548. /**
  21549. * Stops and removes all animations that have been applied to the scene
  21550. */
  21551. Scene.prototype.stopAllAnimations = function () {
  21552. if (this._activeAnimatables) {
  21553. for (var i = 0; i < this._activeAnimatables.length; i++) {
  21554. this._activeAnimatables[i].stop();
  21555. }
  21556. this._activeAnimatables = [];
  21557. }
  21558. };
  21559. Scene.prototype._animate = function () {
  21560. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  21561. return;
  21562. }
  21563. // Getting time
  21564. var now = BABYLON.Tools.Now;
  21565. if (!this._animationTimeLast) {
  21566. if (this._pendingData.length > 0) {
  21567. return;
  21568. }
  21569. this._animationTimeLast = now;
  21570. }
  21571. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  21572. this._animationTime += deltaTime;
  21573. this._animationTimeLast = now;
  21574. for (var index = 0; index < this._activeAnimatables.length; index++) {
  21575. this._activeAnimatables[index]._animate(this._animationTime);
  21576. }
  21577. };
  21578. // Matrix
  21579. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  21580. this._useAlternateCameraConfiguration = active;
  21581. };
  21582. Scene.prototype.getViewMatrix = function () {
  21583. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  21584. };
  21585. Scene.prototype.getProjectionMatrix = function () {
  21586. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  21587. };
  21588. Scene.prototype.getTransformMatrix = function () {
  21589. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  21590. };
  21591. Scene.prototype.setTransformMatrix = function (view, projection) {
  21592. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  21593. return;
  21594. }
  21595. this._viewUpdateFlag = view.updateFlag;
  21596. this._projectionUpdateFlag = projection.updateFlag;
  21597. this._viewMatrix = view;
  21598. this._projectionMatrix = projection;
  21599. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  21600. // Update frustum
  21601. if (!this._frustumPlanes) {
  21602. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  21603. }
  21604. else {
  21605. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  21606. }
  21607. if (this.activeCamera && this.activeCamera._alternateCamera) {
  21608. var otherCamera = this.activeCamera._alternateCamera;
  21609. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  21610. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  21611. }
  21612. if (this._sceneUbo.useUbo) {
  21613. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  21614. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  21615. this._sceneUbo.update();
  21616. }
  21617. };
  21618. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  21619. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  21620. return;
  21621. }
  21622. this._alternateViewUpdateFlag = view.updateFlag;
  21623. this._alternateProjectionUpdateFlag = projection.updateFlag;
  21624. this._alternateViewMatrix = view;
  21625. this._alternateProjectionMatrix = projection;
  21626. if (!this._alternateTransformMatrix) {
  21627. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  21628. }
  21629. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  21630. if (!this._alternateSceneUbo) {
  21631. this._createAlternateUbo();
  21632. }
  21633. if (this._alternateSceneUbo.useUbo) {
  21634. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  21635. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  21636. this._alternateSceneUbo.update();
  21637. }
  21638. };
  21639. Scene.prototype.getSceneUniformBuffer = function () {
  21640. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  21641. };
  21642. // Methods
  21643. Scene.prototype.getUniqueId = function () {
  21644. var result = Scene._uniqueIdCounter;
  21645. Scene._uniqueIdCounter++;
  21646. return result;
  21647. };
  21648. Scene.prototype.addMesh = function (newMesh) {
  21649. this.meshes.push(newMesh);
  21650. //notify the collision coordinator
  21651. if (this.collisionCoordinator) {
  21652. this.collisionCoordinator.onMeshAdded(newMesh);
  21653. }
  21654. newMesh._resyncLightSources();
  21655. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  21656. };
  21657. Scene.prototype.removeMesh = function (toRemove) {
  21658. var index = this.meshes.indexOf(toRemove);
  21659. if (index !== -1) {
  21660. // Remove from the scene if mesh found
  21661. this.meshes.splice(index, 1);
  21662. }
  21663. this.onMeshRemovedObservable.notifyObservers(toRemove);
  21664. return index;
  21665. };
  21666. Scene.prototype.addTransformNode = function (newTransformNode) {
  21667. this.transformNodes.push(newTransformNode);
  21668. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  21669. };
  21670. Scene.prototype.removeTransformNode = function (toRemove) {
  21671. var index = this.transformNodes.indexOf(toRemove);
  21672. if (index !== -1) {
  21673. // Remove from the scene if found
  21674. this.transformNodes.splice(index, 1);
  21675. }
  21676. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  21677. return index;
  21678. };
  21679. Scene.prototype.removeSkeleton = function (toRemove) {
  21680. var index = this.skeletons.indexOf(toRemove);
  21681. if (index !== -1) {
  21682. // Remove from the scene if found
  21683. this.skeletons.splice(index, 1);
  21684. }
  21685. return index;
  21686. };
  21687. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  21688. var index = this.morphTargetManagers.indexOf(toRemove);
  21689. if (index !== -1) {
  21690. // Remove from the scene if found
  21691. this.morphTargetManagers.splice(index, 1);
  21692. }
  21693. return index;
  21694. };
  21695. Scene.prototype.removeLight = function (toRemove) {
  21696. var index = this.lights.indexOf(toRemove);
  21697. if (index !== -1) {
  21698. // Remove from meshes
  21699. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  21700. var mesh = _a[_i];
  21701. mesh._removeLightSource(toRemove);
  21702. }
  21703. // Remove from the scene if mesh found
  21704. this.lights.splice(index, 1);
  21705. this.sortLightsByPriority();
  21706. }
  21707. this.onLightRemovedObservable.notifyObservers(toRemove);
  21708. return index;
  21709. };
  21710. Scene.prototype.removeCamera = function (toRemove) {
  21711. var index = this.cameras.indexOf(toRemove);
  21712. if (index !== -1) {
  21713. // Remove from the scene if mesh found
  21714. this.cameras.splice(index, 1);
  21715. }
  21716. // Remove from activeCameras
  21717. var index2 = this.activeCameras.indexOf(toRemove);
  21718. if (index2 !== -1) {
  21719. // Remove from the scene if mesh found
  21720. this.activeCameras.splice(index2, 1);
  21721. }
  21722. // Reset the activeCamera
  21723. if (this.activeCamera === toRemove) {
  21724. if (this.cameras.length > 0) {
  21725. this.activeCamera = this.cameras[0];
  21726. }
  21727. else {
  21728. this.activeCamera = null;
  21729. }
  21730. }
  21731. this.onCameraRemovedObservable.notifyObservers(toRemove);
  21732. return index;
  21733. };
  21734. Scene.prototype.removeParticleSystem = function (toRemove) {
  21735. var index = this.particleSystems.indexOf(toRemove);
  21736. if (index !== -1) {
  21737. this.particleSystems.splice(index, 1);
  21738. }
  21739. return index;
  21740. };
  21741. ;
  21742. Scene.prototype.removeAnimation = function (toRemove) {
  21743. var index = this.animations.indexOf(toRemove);
  21744. if (index !== -1) {
  21745. this.animations.splice(index, 1);
  21746. }
  21747. return index;
  21748. };
  21749. ;
  21750. Scene.prototype.removeMultiMaterial = function (toRemove) {
  21751. var index = this.multiMaterials.indexOf(toRemove);
  21752. if (index !== -1) {
  21753. this.multiMaterials.splice(index, 1);
  21754. }
  21755. return index;
  21756. };
  21757. ;
  21758. Scene.prototype.removeMaterial = function (toRemove) {
  21759. var index = this.materials.indexOf(toRemove);
  21760. if (index !== -1) {
  21761. this.materials.splice(index, 1);
  21762. }
  21763. return index;
  21764. };
  21765. ;
  21766. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  21767. var index = this.lensFlareSystems.indexOf(toRemove);
  21768. if (index !== -1) {
  21769. this.lensFlareSystems.splice(index, 1);
  21770. }
  21771. return index;
  21772. };
  21773. ;
  21774. Scene.prototype.removeActionManager = function (toRemove) {
  21775. var index = this._actionManagers.indexOf(toRemove);
  21776. if (index !== -1) {
  21777. this._actionManagers.splice(index, 1);
  21778. }
  21779. return index;
  21780. };
  21781. ;
  21782. Scene.prototype.addLight = function (newLight) {
  21783. this.lights.push(newLight);
  21784. this.sortLightsByPriority();
  21785. // Add light to all meshes (To support if the light is removed and then readded)
  21786. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  21787. var mesh = _a[_i];
  21788. if (mesh._lightSources.indexOf(newLight) === -1) {
  21789. mesh._lightSources.push(newLight);
  21790. mesh._resyncLightSources();
  21791. }
  21792. }
  21793. this.onNewLightAddedObservable.notifyObservers(newLight);
  21794. };
  21795. Scene.prototype.sortLightsByPriority = function () {
  21796. if (this.requireLightSorting) {
  21797. this.lights.sort(BABYLON.Light.compareLightsPriority);
  21798. }
  21799. };
  21800. Scene.prototype.addCamera = function (newCamera) {
  21801. this.cameras.push(newCamera);
  21802. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  21803. };
  21804. Scene.prototype.addSkeleton = function (newSkeleton) {
  21805. this.skeletons.push(newSkeleton);
  21806. };
  21807. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  21808. this.particleSystems.push(newParticleSystem);
  21809. };
  21810. Scene.prototype.addAnimation = function (newAnimation) {
  21811. this.animations.push(newAnimation);
  21812. };
  21813. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  21814. this.multiMaterials.push(newMultiMaterial);
  21815. };
  21816. Scene.prototype.addMaterial = function (newMaterial) {
  21817. this.materials.push(newMaterial);
  21818. };
  21819. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  21820. this.morphTargetManagers.push(newMorphTargetManager);
  21821. };
  21822. Scene.prototype.addGeometry = function (newGeometrie) {
  21823. this._geometries.push(newGeometrie);
  21824. };
  21825. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  21826. this.lensFlareSystems.push(newLensFlareSystem);
  21827. };
  21828. Scene.prototype.addActionManager = function (newActionManager) {
  21829. this._actionManagers.push(newActionManager);
  21830. };
  21831. /**
  21832. * Switch active camera
  21833. * @param {Camera} newCamera - new active camera
  21834. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  21835. */
  21836. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  21837. if (attachControl === void 0) { attachControl = true; }
  21838. var canvas = this._engine.getRenderingCanvas();
  21839. if (!canvas) {
  21840. return;
  21841. }
  21842. if (this.activeCamera) {
  21843. this.activeCamera.detachControl(canvas);
  21844. }
  21845. this.activeCamera = newCamera;
  21846. if (attachControl) {
  21847. newCamera.attachControl(canvas);
  21848. }
  21849. };
  21850. /**
  21851. * sets the active camera of the scene using its ID
  21852. * @param {string} id - the camera's ID
  21853. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  21854. * @see activeCamera
  21855. */
  21856. Scene.prototype.setActiveCameraByID = function (id) {
  21857. var camera = this.getCameraByID(id);
  21858. if (camera) {
  21859. this.activeCamera = camera;
  21860. return camera;
  21861. }
  21862. return null;
  21863. };
  21864. /**
  21865. * sets the active camera of the scene using its name
  21866. * @param {string} name - the camera's name
  21867. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  21868. * @see activeCamera
  21869. */
  21870. Scene.prototype.setActiveCameraByName = function (name) {
  21871. var camera = this.getCameraByName(name);
  21872. if (camera) {
  21873. this.activeCamera = camera;
  21874. return camera;
  21875. }
  21876. return null;
  21877. };
  21878. /**
  21879. * get an animation group using its name
  21880. * @param {string} the material's name
  21881. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  21882. */
  21883. Scene.prototype.getAnimationGroupByName = function (name) {
  21884. for (var index = 0; index < this.animationGroups.length; index++) {
  21885. if (this.animationGroups[index].name === name) {
  21886. return this.animationGroups[index];
  21887. }
  21888. }
  21889. return null;
  21890. };
  21891. /**
  21892. * get a material using its id
  21893. * @param {string} the material's ID
  21894. * @return {BABYLON.Material|null} the material or null if none found.
  21895. */
  21896. Scene.prototype.getMaterialByID = function (id) {
  21897. for (var index = 0; index < this.materials.length; index++) {
  21898. if (this.materials[index].id === id) {
  21899. return this.materials[index];
  21900. }
  21901. }
  21902. return null;
  21903. };
  21904. /**
  21905. * get a material using its name
  21906. * @param {string} the material's name
  21907. * @return {BABYLON.Material|null} the material or null if none found.
  21908. */
  21909. Scene.prototype.getMaterialByName = function (name) {
  21910. for (var index = 0; index < this.materials.length; index++) {
  21911. if (this.materials[index].name === name) {
  21912. return this.materials[index];
  21913. }
  21914. }
  21915. return null;
  21916. };
  21917. Scene.prototype.getLensFlareSystemByName = function (name) {
  21918. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  21919. if (this.lensFlareSystems[index].name === name) {
  21920. return this.lensFlareSystems[index];
  21921. }
  21922. }
  21923. return null;
  21924. };
  21925. Scene.prototype.getLensFlareSystemByID = function (id) {
  21926. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  21927. if (this.lensFlareSystems[index].id === id) {
  21928. return this.lensFlareSystems[index];
  21929. }
  21930. }
  21931. return null;
  21932. };
  21933. Scene.prototype.getCameraByID = function (id) {
  21934. for (var index = 0; index < this.cameras.length; index++) {
  21935. if (this.cameras[index].id === id) {
  21936. return this.cameras[index];
  21937. }
  21938. }
  21939. return null;
  21940. };
  21941. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  21942. for (var index = 0; index < this.cameras.length; index++) {
  21943. if (this.cameras[index].uniqueId === uniqueId) {
  21944. return this.cameras[index];
  21945. }
  21946. }
  21947. return null;
  21948. };
  21949. /**
  21950. * get a camera using its name
  21951. * @param {string} the camera's name
  21952. * @return {BABYLON.Camera|null} the camera or null if none found.
  21953. */
  21954. Scene.prototype.getCameraByName = function (name) {
  21955. for (var index = 0; index < this.cameras.length; index++) {
  21956. if (this.cameras[index].name === name) {
  21957. return this.cameras[index];
  21958. }
  21959. }
  21960. return null;
  21961. };
  21962. /**
  21963. * get a bone using its id
  21964. * @param {string} the bone's id
  21965. * @return {BABYLON.Bone|null} the bone or null if not found
  21966. */
  21967. Scene.prototype.getBoneByID = function (id) {
  21968. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  21969. var skeleton = this.skeletons[skeletonIndex];
  21970. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  21971. if (skeleton.bones[boneIndex].id === id) {
  21972. return skeleton.bones[boneIndex];
  21973. }
  21974. }
  21975. }
  21976. return null;
  21977. };
  21978. /**
  21979. * get a bone using its id
  21980. * @param {string} the bone's name
  21981. * @return {BABYLON.Bone|null} the bone or null if not found
  21982. */
  21983. Scene.prototype.getBoneByName = function (name) {
  21984. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  21985. var skeleton = this.skeletons[skeletonIndex];
  21986. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  21987. if (skeleton.bones[boneIndex].name === name) {
  21988. return skeleton.bones[boneIndex];
  21989. }
  21990. }
  21991. }
  21992. return null;
  21993. };
  21994. /**
  21995. * get a light node using its name
  21996. * @param {string} the light's name
  21997. * @return {BABYLON.Light|null} the light or null if none found.
  21998. */
  21999. Scene.prototype.getLightByName = function (name) {
  22000. for (var index = 0; index < this.lights.length; index++) {
  22001. if (this.lights[index].name === name) {
  22002. return this.lights[index];
  22003. }
  22004. }
  22005. return null;
  22006. };
  22007. /**
  22008. * get a light node using its ID
  22009. * @param {string} the light's id
  22010. * @return {BABYLON.Light|null} the light or null if none found.
  22011. */
  22012. Scene.prototype.getLightByID = function (id) {
  22013. for (var index = 0; index < this.lights.length; index++) {
  22014. if (this.lights[index].id === id) {
  22015. return this.lights[index];
  22016. }
  22017. }
  22018. return null;
  22019. };
  22020. /**
  22021. * get a light node using its scene-generated unique ID
  22022. * @param {number} the light's unique id
  22023. * @return {BABYLON.Light|null} the light or null if none found.
  22024. */
  22025. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  22026. for (var index = 0; index < this.lights.length; index++) {
  22027. if (this.lights[index].uniqueId === uniqueId) {
  22028. return this.lights[index];
  22029. }
  22030. }
  22031. return null;
  22032. };
  22033. /**
  22034. * get a particle system by id
  22035. * @param id {number} the particle system id
  22036. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  22037. */
  22038. Scene.prototype.getParticleSystemByID = function (id) {
  22039. for (var index = 0; index < this.particleSystems.length; index++) {
  22040. if (this.particleSystems[index].id === id) {
  22041. return this.particleSystems[index];
  22042. }
  22043. }
  22044. return null;
  22045. };
  22046. /**
  22047. * get a geometry using its ID
  22048. * @param {string} the geometry's id
  22049. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  22050. */
  22051. Scene.prototype.getGeometryByID = function (id) {
  22052. for (var index = 0; index < this._geometries.length; index++) {
  22053. if (this._geometries[index].id === id) {
  22054. return this._geometries[index];
  22055. }
  22056. }
  22057. return null;
  22058. };
  22059. /**
  22060. * add a new geometry to this scene.
  22061. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  22062. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  22063. * @return {boolean} was the geometry added or not
  22064. */
  22065. Scene.prototype.pushGeometry = function (geometry, force) {
  22066. if (!force && this.getGeometryByID(geometry.id)) {
  22067. return false;
  22068. }
  22069. this._geometries.push(geometry);
  22070. //notify the collision coordinator
  22071. if (this.collisionCoordinator) {
  22072. this.collisionCoordinator.onGeometryAdded(geometry);
  22073. }
  22074. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  22075. return true;
  22076. };
  22077. /**
  22078. * Removes an existing geometry
  22079. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  22080. * @return {boolean} was the geometry removed or not
  22081. */
  22082. Scene.prototype.removeGeometry = function (geometry) {
  22083. var index = this._geometries.indexOf(geometry);
  22084. if (index > -1) {
  22085. this._geometries.splice(index, 1);
  22086. //notify the collision coordinator
  22087. if (this.collisionCoordinator) {
  22088. this.collisionCoordinator.onGeometryDeleted(geometry);
  22089. }
  22090. this.onGeometryRemovedObservable.notifyObservers(geometry);
  22091. return true;
  22092. }
  22093. return false;
  22094. };
  22095. Scene.prototype.getGeometries = function () {
  22096. return this._geometries;
  22097. };
  22098. /**
  22099. * Get the first added mesh found of a given ID
  22100. * @param {string} id - the id to search for
  22101. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  22102. */
  22103. Scene.prototype.getMeshByID = function (id) {
  22104. for (var index = 0; index < this.meshes.length; index++) {
  22105. if (this.meshes[index].id === id) {
  22106. return this.meshes[index];
  22107. }
  22108. }
  22109. return null;
  22110. };
  22111. Scene.prototype.getMeshesByID = function (id) {
  22112. return this.meshes.filter(function (m) {
  22113. return m.id === id;
  22114. });
  22115. };
  22116. /**
  22117. * Get the first added transform node found of a given ID
  22118. * @param {string} id - the id to search for
  22119. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  22120. */
  22121. Scene.prototype.getTransformNodeByID = function (id) {
  22122. for (var index = 0; index < this.transformNodes.length; index++) {
  22123. if (this.transformNodes[index].id === id) {
  22124. return this.transformNodes[index];
  22125. }
  22126. }
  22127. return null;
  22128. };
  22129. Scene.prototype.getTransformNodesByID = function (id) {
  22130. return this.transformNodes.filter(function (m) {
  22131. return m.id === id;
  22132. });
  22133. };
  22134. /**
  22135. * Get a mesh with its auto-generated unique id
  22136. * @param {number} uniqueId - the unique id to search for
  22137. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  22138. */
  22139. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  22140. for (var index = 0; index < this.meshes.length; index++) {
  22141. if (this.meshes[index].uniqueId === uniqueId) {
  22142. return this.meshes[index];
  22143. }
  22144. }
  22145. return null;
  22146. };
  22147. /**
  22148. * Get a the last added mesh found of a given ID
  22149. * @param {string} id - the id to search for
  22150. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  22151. */
  22152. Scene.prototype.getLastMeshByID = function (id) {
  22153. for (var index = this.meshes.length - 1; index >= 0; index--) {
  22154. if (this.meshes[index].id === id) {
  22155. return this.meshes[index];
  22156. }
  22157. }
  22158. return null;
  22159. };
  22160. /**
  22161. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  22162. * @param {string} id - the id to search for
  22163. * @return {BABYLON.Node|null} the node found or null if not found at all.
  22164. */
  22165. Scene.prototype.getLastEntryByID = function (id) {
  22166. var index;
  22167. for (index = this.meshes.length - 1; index >= 0; index--) {
  22168. if (this.meshes[index].id === id) {
  22169. return this.meshes[index];
  22170. }
  22171. }
  22172. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  22173. if (this.transformNodes[index].id === id) {
  22174. return this.transformNodes[index];
  22175. }
  22176. }
  22177. for (index = this.cameras.length - 1; index >= 0; index--) {
  22178. if (this.cameras[index].id === id) {
  22179. return this.cameras[index];
  22180. }
  22181. }
  22182. for (index = this.lights.length - 1; index >= 0; index--) {
  22183. if (this.lights[index].id === id) {
  22184. return this.lights[index];
  22185. }
  22186. }
  22187. return null;
  22188. };
  22189. Scene.prototype.getNodeByID = function (id) {
  22190. var mesh = this.getMeshByID(id);
  22191. if (mesh) {
  22192. return mesh;
  22193. }
  22194. var light = this.getLightByID(id);
  22195. if (light) {
  22196. return light;
  22197. }
  22198. var camera = this.getCameraByID(id);
  22199. if (camera) {
  22200. return camera;
  22201. }
  22202. var bone = this.getBoneByID(id);
  22203. return bone;
  22204. };
  22205. Scene.prototype.getNodeByName = function (name) {
  22206. var mesh = this.getMeshByName(name);
  22207. if (mesh) {
  22208. return mesh;
  22209. }
  22210. var light = this.getLightByName(name);
  22211. if (light) {
  22212. return light;
  22213. }
  22214. var camera = this.getCameraByName(name);
  22215. if (camera) {
  22216. return camera;
  22217. }
  22218. var bone = this.getBoneByName(name);
  22219. return bone;
  22220. };
  22221. Scene.prototype.getMeshByName = function (name) {
  22222. for (var index = 0; index < this.meshes.length; index++) {
  22223. if (this.meshes[index].name === name) {
  22224. return this.meshes[index];
  22225. }
  22226. }
  22227. return null;
  22228. };
  22229. Scene.prototype.getTransformNodeByName = function (name) {
  22230. for (var index = 0; index < this.transformNodes.length; index++) {
  22231. if (this.transformNodes[index].name === name) {
  22232. return this.transformNodes[index];
  22233. }
  22234. }
  22235. return null;
  22236. };
  22237. Scene.prototype.getSoundByName = function (name) {
  22238. var index;
  22239. if (BABYLON.AudioEngine) {
  22240. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  22241. if (this.mainSoundTrack.soundCollection[index].name === name) {
  22242. return this.mainSoundTrack.soundCollection[index];
  22243. }
  22244. }
  22245. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  22246. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  22247. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  22248. return this.soundTracks[sdIndex].soundCollection[index];
  22249. }
  22250. }
  22251. }
  22252. }
  22253. return null;
  22254. };
  22255. Scene.prototype.getLastSkeletonByID = function (id) {
  22256. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  22257. if (this.skeletons[index].id === id) {
  22258. return this.skeletons[index];
  22259. }
  22260. }
  22261. return null;
  22262. };
  22263. Scene.prototype.getSkeletonById = function (id) {
  22264. for (var index = 0; index < this.skeletons.length; index++) {
  22265. if (this.skeletons[index].id === id) {
  22266. return this.skeletons[index];
  22267. }
  22268. }
  22269. return null;
  22270. };
  22271. Scene.prototype.getSkeletonByName = function (name) {
  22272. for (var index = 0; index < this.skeletons.length; index++) {
  22273. if (this.skeletons[index].name === name) {
  22274. return this.skeletons[index];
  22275. }
  22276. }
  22277. return null;
  22278. };
  22279. Scene.prototype.getMorphTargetManagerById = function (id) {
  22280. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  22281. if (this.morphTargetManagers[index].uniqueId === id) {
  22282. return this.morphTargetManagers[index];
  22283. }
  22284. }
  22285. return null;
  22286. };
  22287. Scene.prototype.isActiveMesh = function (mesh) {
  22288. return (this._activeMeshes.indexOf(mesh) !== -1);
  22289. };
  22290. /**
  22291. * Return a the first highlight layer of the scene with a given name.
  22292. * @param name The name of the highlight layer to look for.
  22293. * @return The highlight layer if found otherwise null.
  22294. */
  22295. Scene.prototype.getHighlightLayerByName = function (name) {
  22296. for (var index = 0; index < this.highlightLayers.length; index++) {
  22297. if (this.highlightLayers[index].name === name) {
  22298. return this.highlightLayers[index];
  22299. }
  22300. }
  22301. return null;
  22302. };
  22303. Object.defineProperty(Scene.prototype, "uid", {
  22304. /**
  22305. * Return a unique id as a string which can serve as an identifier for the scene
  22306. */
  22307. get: function () {
  22308. if (!this._uid) {
  22309. this._uid = BABYLON.Tools.RandomId();
  22310. }
  22311. return this._uid;
  22312. },
  22313. enumerable: true,
  22314. configurable: true
  22315. });
  22316. /**
  22317. * Add an externaly attached data from its key.
  22318. * This method call will fail and return false, if such key already exists.
  22319. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  22320. * @param key the unique key that identifies the data
  22321. * @param data the data object to associate to the key for this Engine instance
  22322. * @return true if no such key were already present and the data was added successfully, false otherwise
  22323. */
  22324. Scene.prototype.addExternalData = function (key, data) {
  22325. if (!this._externalData) {
  22326. this._externalData = new BABYLON.StringDictionary();
  22327. }
  22328. return this._externalData.add(key, data);
  22329. };
  22330. /**
  22331. * Get an externaly attached data from its key
  22332. * @param key the unique key that identifies the data
  22333. * @return the associated data, if present (can be null), or undefined if not present
  22334. */
  22335. Scene.prototype.getExternalData = function (key) {
  22336. if (!this._externalData) {
  22337. return null;
  22338. }
  22339. return this._externalData.get(key);
  22340. };
  22341. /**
  22342. * Get an externaly attached data from its key, create it using a factory if it's not already present
  22343. * @param key the unique key that identifies the data
  22344. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  22345. * @return the associated data, can be null if the factory returned null.
  22346. */
  22347. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  22348. if (!this._externalData) {
  22349. this._externalData = new BABYLON.StringDictionary();
  22350. }
  22351. return this._externalData.getOrAddWithFactory(key, factory);
  22352. };
  22353. /**
  22354. * Remove an externaly attached data from the Engine instance
  22355. * @param key the unique key that identifies the data
  22356. * @return true if the data was successfully removed, false if it doesn't exist
  22357. */
  22358. Scene.prototype.removeExternalData = function (key) {
  22359. return this._externalData.remove(key);
  22360. };
  22361. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  22362. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  22363. if (mesh.showSubMeshesBoundingBox) {
  22364. var boundingInfo = subMesh.getBoundingInfo();
  22365. if (boundingInfo !== null && boundingInfo !== undefined) {
  22366. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  22367. }
  22368. }
  22369. var material = subMesh.getMaterial();
  22370. if (material !== null && material !== undefined) {
  22371. // Render targets
  22372. if (material.getRenderTargetTextures !== undefined) {
  22373. if (this._processedMaterials.indexOf(material) === -1) {
  22374. this._processedMaterials.push(material);
  22375. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  22376. }
  22377. }
  22378. // Dispatch
  22379. this._activeIndices.addCount(subMesh.indexCount, false);
  22380. this._renderingManager.dispatch(subMesh, mesh, material);
  22381. }
  22382. }
  22383. };
  22384. Scene.prototype._isInIntermediateRendering = function () {
  22385. return this._intermediateRendering;
  22386. };
  22387. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  22388. this._activeMeshCandidateProvider = provider;
  22389. };
  22390. Scene.prototype.getActiveMeshCandidateProvider = function () {
  22391. return this._activeMeshCandidateProvider;
  22392. };
  22393. /**
  22394. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  22395. */
  22396. Scene.prototype.freezeActiveMeshes = function () {
  22397. this._evaluateActiveMeshes();
  22398. this._activeMeshesFrozen = true;
  22399. return this;
  22400. };
  22401. /**
  22402. * Use this function to restart evaluating active meshes on every frame
  22403. */
  22404. Scene.prototype.unfreezeActiveMeshes = function () {
  22405. this._activeMeshesFrozen = false;
  22406. return this;
  22407. };
  22408. Scene.prototype._evaluateActiveMeshes = function () {
  22409. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  22410. return;
  22411. }
  22412. if (!this.activeCamera) {
  22413. return;
  22414. }
  22415. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  22416. this.activeCamera._activeMeshes.reset();
  22417. this._activeMeshes.reset();
  22418. this._renderingManager.reset();
  22419. this._processedMaterials.reset();
  22420. this._activeParticleSystems.reset();
  22421. this._activeSkeletons.reset();
  22422. this._softwareSkinnedMeshes.reset();
  22423. if (this._boundingBoxRenderer) {
  22424. this._boundingBoxRenderer.reset();
  22425. }
  22426. // Meshes
  22427. var meshes;
  22428. var len;
  22429. var checkIsEnabled = true;
  22430. // Determine mesh candidates
  22431. if (this._activeMeshCandidateProvider !== undefined) {
  22432. // Use _activeMeshCandidateProvider
  22433. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  22434. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  22435. if (meshes !== undefined) {
  22436. len = meshes.length;
  22437. }
  22438. else {
  22439. len = 0;
  22440. }
  22441. }
  22442. else if (this._selectionOctree !== undefined) {
  22443. // Octree
  22444. var selection = this._selectionOctree.select(this._frustumPlanes);
  22445. meshes = selection.data;
  22446. len = selection.length;
  22447. }
  22448. else {
  22449. // Full scene traversal
  22450. len = this.meshes.length;
  22451. meshes = this.meshes;
  22452. }
  22453. // Check each mesh
  22454. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  22455. mesh = meshes[meshIndex];
  22456. if (mesh.isBlocked) {
  22457. continue;
  22458. }
  22459. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  22460. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  22461. continue;
  22462. }
  22463. mesh.computeWorldMatrix();
  22464. // Intersections
  22465. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  22466. this._meshesForIntersections.pushNoDuplicate(mesh);
  22467. }
  22468. // Switch to current LOD
  22469. meshLOD = mesh.getLOD(this.activeCamera);
  22470. if (meshLOD === undefined || meshLOD === null) {
  22471. continue;
  22472. }
  22473. mesh._preActivate();
  22474. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  22475. this._activeMeshes.push(mesh);
  22476. this.activeCamera._activeMeshes.push(mesh);
  22477. mesh._activate(this._renderId);
  22478. if (meshLOD !== mesh) {
  22479. meshLOD._activate(this._renderId);
  22480. }
  22481. this._activeMesh(mesh, meshLOD);
  22482. }
  22483. }
  22484. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  22485. // Particle systems
  22486. if (this.particlesEnabled) {
  22487. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  22488. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  22489. var particleSystem = this.particleSystems[particleIndex];
  22490. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  22491. continue;
  22492. }
  22493. var emitter = particleSystem.emitter;
  22494. if (!emitter.position || emitter.isEnabled()) {
  22495. this._activeParticleSystems.push(particleSystem);
  22496. particleSystem.animate();
  22497. this._renderingManager.dispatchParticles(particleSystem);
  22498. }
  22499. }
  22500. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  22501. }
  22502. };
  22503. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  22504. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  22505. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  22506. mesh.skeleton.prepare();
  22507. }
  22508. if (!mesh.computeBonesUsingShaders) {
  22509. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  22510. }
  22511. }
  22512. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  22513. var boundingInfo = sourceMesh.getBoundingInfo();
  22514. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  22515. }
  22516. if (mesh !== undefined && mesh !== null
  22517. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  22518. // Submeshes Octrees
  22519. var len;
  22520. var subMeshes;
  22521. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  22522. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  22523. len = intersections.length;
  22524. subMeshes = intersections.data;
  22525. }
  22526. else {
  22527. subMeshes = mesh.subMeshes;
  22528. len = subMeshes.length;
  22529. }
  22530. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  22531. subMesh = subMeshes[subIndex];
  22532. this._evaluateSubMesh(subMesh, mesh);
  22533. }
  22534. }
  22535. };
  22536. Scene.prototype.updateTransformMatrix = function (force) {
  22537. if (!this.activeCamera) {
  22538. return;
  22539. }
  22540. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  22541. };
  22542. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  22543. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  22544. };
  22545. Scene.prototype._renderForCamera = function (camera) {
  22546. if (camera && camera._skipRendering) {
  22547. return;
  22548. }
  22549. var engine = this._engine;
  22550. this.activeCamera = camera;
  22551. if (!this.activeCamera)
  22552. throw new Error("Active camera not set");
  22553. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  22554. // Viewport
  22555. engine.setViewport(this.activeCamera.viewport);
  22556. // Camera
  22557. this.resetCachedMaterial();
  22558. this._renderId++;
  22559. this.activeCamera.update();
  22560. this.updateTransformMatrix();
  22561. if (camera._alternateCamera) {
  22562. this.updateAlternateTransformMatrix(camera._alternateCamera);
  22563. this._alternateRendering = true;
  22564. }
  22565. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  22566. // Meshes
  22567. this._evaluateActiveMeshes();
  22568. // Software skinning
  22569. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  22570. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  22571. mesh.applySkeleton(mesh.skeleton);
  22572. }
  22573. // Render targets
  22574. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  22575. var needsRestoreFrameBuffer = false;
  22576. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  22577. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  22578. }
  22579. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  22580. this._intermediateRendering = true;
  22581. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  22582. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  22583. var renderTarget = this._renderTargets.data[renderIndex];
  22584. if (renderTarget._shouldRender()) {
  22585. this._renderId++;
  22586. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  22587. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  22588. }
  22589. }
  22590. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  22591. this._intermediateRendering = false;
  22592. this._renderId++;
  22593. needsRestoreFrameBuffer = true; // Restore back buffer
  22594. }
  22595. // Render HighlightLayer Texture
  22596. var stencilState = this._engine.getStencilBuffer();
  22597. var renderhighlights = false;
  22598. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  22599. this._intermediateRendering = true;
  22600. for (var i = 0; i < this.highlightLayers.length; i++) {
  22601. var highlightLayer = this.highlightLayers[i];
  22602. if (highlightLayer.shouldRender() &&
  22603. (!highlightLayer.camera ||
  22604. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  22605. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  22606. renderhighlights = true;
  22607. var renderTarget = highlightLayer._mainTexture;
  22608. if (renderTarget._shouldRender()) {
  22609. this._renderId++;
  22610. renderTarget.render(false, false);
  22611. needsRestoreFrameBuffer = true;
  22612. }
  22613. }
  22614. }
  22615. this._intermediateRendering = false;
  22616. this._renderId++;
  22617. }
  22618. if (needsRestoreFrameBuffer) {
  22619. engine.restoreDefaultFramebuffer(); // Restore back buffer
  22620. }
  22621. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  22622. // Prepare Frame
  22623. this.postProcessManager._prepareFrame();
  22624. // Backgrounds
  22625. var layerIndex;
  22626. var layer;
  22627. if (this.layers.length) {
  22628. engine.setDepthBuffer(false);
  22629. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  22630. layer = this.layers[layerIndex];
  22631. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  22632. layer.render();
  22633. }
  22634. }
  22635. engine.setDepthBuffer(true);
  22636. }
  22637. // Activate HighlightLayer stencil
  22638. if (renderhighlights) {
  22639. this._engine.setStencilBuffer(true);
  22640. }
  22641. // Render
  22642. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  22643. this._renderingManager.render(null, null, true, true);
  22644. this.onAfterDrawPhaseObservable.notifyObservers(this);
  22645. // Restore HighlightLayer stencil
  22646. if (renderhighlights) {
  22647. this._engine.setStencilBuffer(stencilState);
  22648. }
  22649. // Bounding boxes
  22650. if (this._boundingBoxRenderer) {
  22651. this._boundingBoxRenderer.render();
  22652. }
  22653. // Lens flares
  22654. if (this.lensFlaresEnabled) {
  22655. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  22656. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  22657. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  22658. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  22659. lensFlareSystem.render();
  22660. }
  22661. }
  22662. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  22663. }
  22664. // Foregrounds
  22665. if (this.layers.length) {
  22666. engine.setDepthBuffer(false);
  22667. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  22668. layer = this.layers[layerIndex];
  22669. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  22670. layer.render();
  22671. }
  22672. }
  22673. engine.setDepthBuffer(true);
  22674. }
  22675. // Highlight Layer
  22676. if (renderhighlights) {
  22677. engine.setDepthBuffer(false);
  22678. for (var i = 0; i < this.highlightLayers.length; i++) {
  22679. if (this.highlightLayers[i].shouldRender()) {
  22680. this.highlightLayers[i].render();
  22681. }
  22682. }
  22683. engine.setDepthBuffer(true);
  22684. }
  22685. // Finalize frame
  22686. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  22687. // Reset some special arrays
  22688. this._renderTargets.reset();
  22689. this._alternateRendering = false;
  22690. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  22691. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  22692. };
  22693. Scene.prototype._processSubCameras = function (camera) {
  22694. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  22695. this._renderForCamera(camera);
  22696. return;
  22697. }
  22698. // Update camera
  22699. if (this.activeCamera) {
  22700. this.activeCamera.update();
  22701. }
  22702. // rig cameras
  22703. for (var index = 0; index < camera._rigCameras.length; index++) {
  22704. this._renderForCamera(camera._rigCameras[index]);
  22705. }
  22706. this.activeCamera = camera;
  22707. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  22708. };
  22709. Scene.prototype._checkIntersections = function () {
  22710. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  22711. var sourceMesh = this._meshesForIntersections.data[index];
  22712. if (!sourceMesh.actionManager) {
  22713. continue;
  22714. }
  22715. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  22716. var action = sourceMesh.actionManager.actions[actionIndex];
  22717. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22718. var parameters = action.getTriggerParameter();
  22719. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  22720. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  22721. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  22722. if (areIntersecting && currentIntersectionInProgress === -1) {
  22723. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  22724. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  22725. sourceMesh._intersectionsInProgress.push(otherMesh);
  22726. }
  22727. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22728. sourceMesh._intersectionsInProgress.push(otherMesh);
  22729. }
  22730. }
  22731. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  22732. //They intersected, and now they don't.
  22733. //is this trigger an exit trigger? execute an event.
  22734. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22735. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  22736. }
  22737. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  22738. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22739. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  22740. }
  22741. }
  22742. }
  22743. }
  22744. }
  22745. };
  22746. Scene.prototype.render = function () {
  22747. if (this.isDisposed) {
  22748. return;
  22749. }
  22750. this._activeParticles.fetchNewFrame();
  22751. this._totalVertices.fetchNewFrame();
  22752. this._activeIndices.fetchNewFrame();
  22753. this._activeBones.fetchNewFrame();
  22754. this._meshesForIntersections.reset();
  22755. this.resetCachedMaterial();
  22756. this.onBeforeAnimationsObservable.notifyObservers(this);
  22757. // Actions
  22758. if (this.actionManager) {
  22759. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  22760. }
  22761. //Simplification Queue
  22762. if (this.simplificationQueue && !this.simplificationQueue.running) {
  22763. this.simplificationQueue.executeNext();
  22764. }
  22765. if (this._engine.isDeterministicLockStep()) {
  22766. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  22767. var defaultFPS = (60.0 / 1000.0);
  22768. var defaultFrameTime = 1000 / 60; // frame time in MS
  22769. if (this._physicsEngine) {
  22770. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  22771. }
  22772. var stepsTaken = 0;
  22773. var maxSubSteps = this._engine.getLockstepMaxSteps();
  22774. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  22775. internalSteps = Math.min(internalSteps, maxSubSteps);
  22776. do {
  22777. this.onBeforeStepObservable.notifyObservers(this);
  22778. // Animations
  22779. this._animationRatio = defaultFrameTime * defaultFPS;
  22780. this._animate();
  22781. this.onAfterAnimationsObservable.notifyObservers(this);
  22782. // Physics
  22783. if (this._physicsEngine) {
  22784. this.onBeforePhysicsObservable.notifyObservers(this);
  22785. this._physicsEngine._step(defaultFrameTime / 1000);
  22786. this.onAfterPhysicsObservable.notifyObservers(this);
  22787. }
  22788. this.onAfterStepObservable.notifyObservers(this);
  22789. this._currentStepId++;
  22790. stepsTaken++;
  22791. deltaTime -= defaultFrameTime;
  22792. } while (deltaTime > 0 && stepsTaken < internalSteps);
  22793. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  22794. }
  22795. else {
  22796. // Animations
  22797. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  22798. this._animationRatio = deltaTime * (60.0 / 1000.0);
  22799. this._animate();
  22800. this.onAfterAnimationsObservable.notifyObservers(this);
  22801. // Physics
  22802. if (this._physicsEngine) {
  22803. this.onBeforePhysicsObservable.notifyObservers(this);
  22804. this._physicsEngine._step(deltaTime / 1000.0);
  22805. this.onAfterPhysicsObservable.notifyObservers(this);
  22806. }
  22807. }
  22808. // update gamepad manager
  22809. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  22810. this._gamepadManager._checkGamepadsStatus();
  22811. }
  22812. // Before render
  22813. this.onBeforeRenderObservable.notifyObservers(this);
  22814. // Customs render targets
  22815. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  22816. var engine = this.getEngine();
  22817. var currentActiveCamera = this.activeCamera;
  22818. if (this.renderTargetsEnabled) {
  22819. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  22820. this._intermediateRendering = true;
  22821. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  22822. var renderTarget = this.customRenderTargets[customIndex];
  22823. if (renderTarget._shouldRender()) {
  22824. this._renderId++;
  22825. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  22826. if (!this.activeCamera)
  22827. throw new Error("Active camera not set");
  22828. // Viewport
  22829. engine.setViewport(this.activeCamera.viewport);
  22830. // Camera
  22831. this.updateTransformMatrix();
  22832. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  22833. }
  22834. }
  22835. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  22836. this._intermediateRendering = false;
  22837. this._renderId++;
  22838. }
  22839. // Restore back buffer
  22840. if (this.customRenderTargets.length > 0) {
  22841. engine.restoreDefaultFramebuffer();
  22842. }
  22843. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  22844. this.activeCamera = currentActiveCamera;
  22845. // Procedural textures
  22846. if (this.proceduralTexturesEnabled) {
  22847. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  22848. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  22849. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  22850. if (proceduralTexture._shouldRender()) {
  22851. proceduralTexture.render();
  22852. }
  22853. }
  22854. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  22855. }
  22856. // Clear
  22857. if (this.autoClearDepthAndStencil || this.autoClear) {
  22858. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  22859. }
  22860. // Shadows
  22861. if (this.shadowsEnabled) {
  22862. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  22863. var light = this.lights[lightIndex];
  22864. var shadowGenerator = light.getShadowGenerator();
  22865. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  22866. var shadowMap = (shadowGenerator.getShadowMap());
  22867. if (this.textures.indexOf(shadowMap) !== -1) {
  22868. this._renderTargets.push(shadowMap);
  22869. }
  22870. }
  22871. }
  22872. }
  22873. // Depth renderer
  22874. if (this._depthRenderer) {
  22875. this._renderTargets.push(this._depthRenderer.getDepthMap());
  22876. }
  22877. // Geometry renderer
  22878. if (this._geometryBufferRenderer) {
  22879. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  22880. }
  22881. // RenderPipeline
  22882. if (this._postProcessRenderPipelineManager) {
  22883. this._postProcessRenderPipelineManager.update();
  22884. }
  22885. // Multi-cameras?
  22886. if (this.activeCameras.length > 0) {
  22887. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  22888. if (cameraIndex > 0) {
  22889. this._engine.clear(null, false, true, true);
  22890. }
  22891. this._processSubCameras(this.activeCameras[cameraIndex]);
  22892. }
  22893. }
  22894. else {
  22895. if (!this.activeCamera) {
  22896. throw new Error("No camera defined");
  22897. }
  22898. this._processSubCameras(this.activeCamera);
  22899. }
  22900. // Intersection checks
  22901. this._checkIntersections();
  22902. // Update the audio listener attached to the camera
  22903. if (BABYLON.AudioEngine) {
  22904. this._updateAudioParameters();
  22905. }
  22906. // After render
  22907. if (this.afterRender) {
  22908. this.afterRender();
  22909. }
  22910. this.onAfterRenderObservable.notifyObservers(this);
  22911. // Cleaning
  22912. for (var index = 0; index < this._toBeDisposed.length; index++) {
  22913. var data = this._toBeDisposed.data[index];
  22914. if (data) {
  22915. data.dispose();
  22916. }
  22917. this._toBeDisposed[index] = null;
  22918. }
  22919. this._toBeDisposed.reset();
  22920. if (this.dumpNextRenderTargets) {
  22921. this.dumpNextRenderTargets = false;
  22922. }
  22923. this._activeBones.addCount(0, true);
  22924. this._activeIndices.addCount(0, true);
  22925. this._activeParticles.addCount(0, true);
  22926. };
  22927. Scene.prototype._updateAudioParameters = function () {
  22928. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  22929. return;
  22930. }
  22931. var listeningCamera;
  22932. var audioEngine = BABYLON.Engine.audioEngine;
  22933. if (this.activeCameras.length > 0) {
  22934. listeningCamera = this.activeCameras[0];
  22935. }
  22936. else {
  22937. listeningCamera = this.activeCamera;
  22938. }
  22939. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  22940. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  22941. // for VR cameras
  22942. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  22943. listeningCamera = listeningCamera.rigCameras[0];
  22944. }
  22945. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  22946. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  22947. cameraDirection.normalize();
  22948. // To avoid some errors on GearVR
  22949. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  22950. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  22951. }
  22952. var i;
  22953. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22954. var sound = this.mainSoundTrack.soundCollection[i];
  22955. if (sound.useCustomAttenuation) {
  22956. sound.updateDistanceFromListener();
  22957. }
  22958. }
  22959. for (i = 0; i < this.soundTracks.length; i++) {
  22960. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22961. sound = this.soundTracks[i].soundCollection[j];
  22962. if (sound.useCustomAttenuation) {
  22963. sound.updateDistanceFromListener();
  22964. }
  22965. }
  22966. }
  22967. }
  22968. };
  22969. Object.defineProperty(Scene.prototype, "audioEnabled", {
  22970. // Audio
  22971. get: function () {
  22972. return this._audioEnabled;
  22973. },
  22974. set: function (value) {
  22975. this._audioEnabled = value;
  22976. if (BABYLON.AudioEngine) {
  22977. if (this._audioEnabled) {
  22978. this._enableAudio();
  22979. }
  22980. else {
  22981. this._disableAudio();
  22982. }
  22983. }
  22984. },
  22985. enumerable: true,
  22986. configurable: true
  22987. });
  22988. Scene.prototype._disableAudio = function () {
  22989. var i;
  22990. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22991. this.mainSoundTrack.soundCollection[i].pause();
  22992. }
  22993. for (i = 0; i < this.soundTracks.length; i++) {
  22994. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22995. this.soundTracks[i].soundCollection[j].pause();
  22996. }
  22997. }
  22998. };
  22999. Scene.prototype._enableAudio = function () {
  23000. var i;
  23001. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  23002. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  23003. this.mainSoundTrack.soundCollection[i].play();
  23004. }
  23005. }
  23006. for (i = 0; i < this.soundTracks.length; i++) {
  23007. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  23008. if (this.soundTracks[i].soundCollection[j].isPaused) {
  23009. this.soundTracks[i].soundCollection[j].play();
  23010. }
  23011. }
  23012. }
  23013. };
  23014. Object.defineProperty(Scene.prototype, "headphone", {
  23015. get: function () {
  23016. return this._headphone;
  23017. },
  23018. set: function (value) {
  23019. this._headphone = value;
  23020. if (BABYLON.AudioEngine) {
  23021. if (this._headphone) {
  23022. this._switchAudioModeForHeadphones();
  23023. }
  23024. else {
  23025. this._switchAudioModeForNormalSpeakers();
  23026. }
  23027. }
  23028. },
  23029. enumerable: true,
  23030. configurable: true
  23031. });
  23032. Scene.prototype._switchAudioModeForHeadphones = function () {
  23033. this.mainSoundTrack.switchPanningModelToHRTF();
  23034. for (var i = 0; i < this.soundTracks.length; i++) {
  23035. this.soundTracks[i].switchPanningModelToHRTF();
  23036. }
  23037. };
  23038. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  23039. this.mainSoundTrack.switchPanningModelToEqualPower();
  23040. for (var i = 0; i < this.soundTracks.length; i++) {
  23041. this.soundTracks[i].switchPanningModelToEqualPower();
  23042. }
  23043. };
  23044. Scene.prototype.enableDepthRenderer = function () {
  23045. if (this._depthRenderer) {
  23046. return this._depthRenderer;
  23047. }
  23048. this._depthRenderer = new BABYLON.DepthRenderer(this);
  23049. return this._depthRenderer;
  23050. };
  23051. Scene.prototype.disableDepthRenderer = function () {
  23052. if (!this._depthRenderer) {
  23053. return;
  23054. }
  23055. this._depthRenderer.dispose();
  23056. this._depthRenderer = null;
  23057. };
  23058. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  23059. if (ratio === void 0) { ratio = 1; }
  23060. if (this._geometryBufferRenderer) {
  23061. return this._geometryBufferRenderer;
  23062. }
  23063. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  23064. if (!this._geometryBufferRenderer.isSupported) {
  23065. this._geometryBufferRenderer = null;
  23066. }
  23067. return this._geometryBufferRenderer;
  23068. };
  23069. Scene.prototype.disableGeometryBufferRenderer = function () {
  23070. if (!this._geometryBufferRenderer) {
  23071. return;
  23072. }
  23073. this._geometryBufferRenderer.dispose();
  23074. this._geometryBufferRenderer = null;
  23075. };
  23076. Scene.prototype.freezeMaterials = function () {
  23077. for (var i = 0; i < this.materials.length; i++) {
  23078. this.materials[i].freeze();
  23079. }
  23080. };
  23081. Scene.prototype.unfreezeMaterials = function () {
  23082. for (var i = 0; i < this.materials.length; i++) {
  23083. this.materials[i].unfreeze();
  23084. }
  23085. };
  23086. Scene.prototype.dispose = function () {
  23087. this.beforeRender = null;
  23088. this.afterRender = null;
  23089. this.skeletons = [];
  23090. this.morphTargetManagers = [];
  23091. this.importedMeshesFiles = new Array();
  23092. this.stopAllAnimations();
  23093. this.resetCachedMaterial();
  23094. if (this._depthRenderer) {
  23095. this._depthRenderer.dispose();
  23096. }
  23097. if (this._gamepadManager) {
  23098. this._gamepadManager.dispose();
  23099. this._gamepadManager = null;
  23100. }
  23101. // Smart arrays
  23102. if (this.activeCamera) {
  23103. this.activeCamera._activeMeshes.dispose();
  23104. this.activeCamera = null;
  23105. }
  23106. this._activeMeshes.dispose();
  23107. this._renderingManager.dispose();
  23108. this._processedMaterials.dispose();
  23109. this._activeParticleSystems.dispose();
  23110. this._activeSkeletons.dispose();
  23111. this._softwareSkinnedMeshes.dispose();
  23112. this._renderTargets.dispose();
  23113. if (this._boundingBoxRenderer) {
  23114. this._boundingBoxRenderer.dispose();
  23115. }
  23116. this._meshesForIntersections.dispose();
  23117. this._toBeDisposed.dispose();
  23118. // Abort active requests
  23119. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  23120. var request = _a[_i];
  23121. request.abort();
  23122. }
  23123. // Debug layer
  23124. if (this._debugLayer) {
  23125. this._debugLayer.hide();
  23126. }
  23127. // Events
  23128. this.onDisposeObservable.notifyObservers(this);
  23129. this.onDisposeObservable.clear();
  23130. this.onBeforeRenderObservable.clear();
  23131. this.onAfterRenderObservable.clear();
  23132. this.OnBeforeRenderTargetsRenderObservable.clear();
  23133. this.OnAfterRenderTargetsRenderObservable.clear();
  23134. this.onAfterStepObservable.clear();
  23135. this.onBeforeStepObservable.clear();
  23136. this.onBeforeActiveMeshesEvaluationObservable.clear();
  23137. this.onAfterActiveMeshesEvaluationObservable.clear();
  23138. this.onBeforeParticlesRenderingObservable.clear();
  23139. this.onAfterParticlesRenderingObservable.clear();
  23140. this.onBeforeSpritesRenderingObservable.clear();
  23141. this.onAfterSpritesRenderingObservable.clear();
  23142. this.onBeforeDrawPhaseObservable.clear();
  23143. this.onAfterDrawPhaseObservable.clear();
  23144. this.onBeforePhysicsObservable.clear();
  23145. this.onAfterPhysicsObservable.clear();
  23146. this.onBeforeAnimationsObservable.clear();
  23147. this.onAfterAnimationsObservable.clear();
  23148. this.onDataLoadedObservable.clear();
  23149. this.detachControl();
  23150. // Release sounds & sounds tracks
  23151. if (BABYLON.AudioEngine) {
  23152. this.disposeSounds();
  23153. }
  23154. // VR Helper
  23155. if (this.VRHelper) {
  23156. this.VRHelper.dispose();
  23157. }
  23158. // Detach cameras
  23159. var canvas = this._engine.getRenderingCanvas();
  23160. if (canvas) {
  23161. var index;
  23162. for (index = 0; index < this.cameras.length; index++) {
  23163. this.cameras[index].detachControl(canvas);
  23164. }
  23165. }
  23166. // Release animation groups
  23167. while (this.animationGroups.length) {
  23168. this.animationGroups[0].dispose();
  23169. }
  23170. // Release lights
  23171. while (this.lights.length) {
  23172. this.lights[0].dispose();
  23173. }
  23174. // Release meshes
  23175. while (this.meshes.length) {
  23176. this.meshes[0].dispose(true);
  23177. }
  23178. while (this.transformNodes.length) {
  23179. this.removeTransformNode(this.transformNodes[0]);
  23180. }
  23181. // Release cameras
  23182. while (this.cameras.length) {
  23183. this.cameras[0].dispose();
  23184. }
  23185. // Release materials
  23186. if (this.defaultMaterial) {
  23187. this.defaultMaterial.dispose();
  23188. }
  23189. while (this.multiMaterials.length) {
  23190. this.multiMaterials[0].dispose();
  23191. }
  23192. while (this.materials.length) {
  23193. this.materials[0].dispose();
  23194. }
  23195. // Release particles
  23196. while (this.particleSystems.length) {
  23197. this.particleSystems[0].dispose();
  23198. }
  23199. // Release sprites
  23200. while (this.spriteManagers.length) {
  23201. this.spriteManagers[0].dispose();
  23202. }
  23203. // Release postProcesses
  23204. while (this.postProcesses.length) {
  23205. this.postProcesses[0].dispose();
  23206. }
  23207. // Release layers
  23208. while (this.layers.length) {
  23209. this.layers[0].dispose();
  23210. }
  23211. while (this.highlightLayers.length) {
  23212. this.highlightLayers[0].dispose();
  23213. }
  23214. // Release textures
  23215. while (this.textures.length) {
  23216. this.textures[0].dispose();
  23217. }
  23218. // Release UBO
  23219. this._sceneUbo.dispose();
  23220. if (this._alternateSceneUbo) {
  23221. this._alternateSceneUbo.dispose();
  23222. }
  23223. // Post-processes
  23224. this.postProcessManager.dispose();
  23225. if (this._postProcessRenderPipelineManager) {
  23226. this._postProcessRenderPipelineManager.dispose();
  23227. }
  23228. // Physics
  23229. if (this._physicsEngine) {
  23230. this.disablePhysicsEngine();
  23231. }
  23232. // Remove from engine
  23233. index = this._engine.scenes.indexOf(this);
  23234. if (index > -1) {
  23235. this._engine.scenes.splice(index, 1);
  23236. }
  23237. this._engine.wipeCaches(true);
  23238. this._isDisposed = true;
  23239. };
  23240. Object.defineProperty(Scene.prototype, "isDisposed", {
  23241. get: function () {
  23242. return this._isDisposed;
  23243. },
  23244. enumerable: true,
  23245. configurable: true
  23246. });
  23247. // Release sounds & sounds tracks
  23248. Scene.prototype.disposeSounds = function () {
  23249. if (!this._mainSoundTrack) {
  23250. return;
  23251. }
  23252. this.mainSoundTrack.dispose();
  23253. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  23254. this.soundTracks[scIndex].dispose();
  23255. }
  23256. };
  23257. // Octrees
  23258. Scene.prototype.getWorldExtends = function () {
  23259. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  23260. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  23261. for (var index = 0; index < this.meshes.length; index++) {
  23262. var mesh = this.meshes[index];
  23263. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  23264. continue;
  23265. }
  23266. mesh.computeWorldMatrix(true);
  23267. var boundingInfo = mesh.getBoundingInfo();
  23268. var minBox = boundingInfo.boundingBox.minimumWorld;
  23269. var maxBox = boundingInfo.boundingBox.maximumWorld;
  23270. BABYLON.Tools.CheckExtends(minBox, min, max);
  23271. BABYLON.Tools.CheckExtends(maxBox, min, max);
  23272. }
  23273. return {
  23274. min: min,
  23275. max: max
  23276. };
  23277. };
  23278. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  23279. if (maxCapacity === void 0) { maxCapacity = 64; }
  23280. if (maxDepth === void 0) { maxDepth = 2; }
  23281. if (!this._selectionOctree) {
  23282. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  23283. }
  23284. var worldExtends = this.getWorldExtends();
  23285. // Update octree
  23286. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  23287. return this._selectionOctree;
  23288. };
  23289. // Picking
  23290. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  23291. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  23292. var result = BABYLON.Ray.Zero();
  23293. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  23294. return result;
  23295. };
  23296. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  23297. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  23298. var engine = this._engine;
  23299. if (!camera) {
  23300. if (!this.activeCamera)
  23301. throw new Error("Active camera not set");
  23302. camera = this.activeCamera;
  23303. }
  23304. var cameraViewport = camera.viewport;
  23305. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  23306. // Moving coordinates to local viewport world
  23307. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  23308. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  23309. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  23310. return this;
  23311. };
  23312. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  23313. var result = BABYLON.Ray.Zero();
  23314. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  23315. return result;
  23316. };
  23317. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  23318. if (!BABYLON.PickingInfo) {
  23319. return this;
  23320. }
  23321. var engine = this._engine;
  23322. if (!camera) {
  23323. if (!this.activeCamera)
  23324. throw new Error("Active camera not set");
  23325. camera = this.activeCamera;
  23326. }
  23327. var cameraViewport = camera.viewport;
  23328. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  23329. var identity = BABYLON.Matrix.Identity();
  23330. // Moving coordinates to local viewport world
  23331. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  23332. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  23333. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  23334. return this;
  23335. };
  23336. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  23337. if (!BABYLON.PickingInfo) {
  23338. return null;
  23339. }
  23340. var pickingInfo = null;
  23341. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  23342. var mesh = this.meshes[meshIndex];
  23343. if (predicate) {
  23344. if (!predicate(mesh)) {
  23345. continue;
  23346. }
  23347. }
  23348. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  23349. continue;
  23350. }
  23351. var world = mesh.getWorldMatrix();
  23352. var ray = rayFunction(world);
  23353. var result = mesh.intersects(ray, fastCheck);
  23354. if (!result || !result.hit)
  23355. continue;
  23356. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  23357. continue;
  23358. pickingInfo = result;
  23359. if (fastCheck) {
  23360. break;
  23361. }
  23362. }
  23363. return pickingInfo || new BABYLON.PickingInfo();
  23364. };
  23365. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  23366. if (!BABYLON.PickingInfo) {
  23367. return null;
  23368. }
  23369. var pickingInfos = new Array();
  23370. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  23371. var mesh = this.meshes[meshIndex];
  23372. if (predicate) {
  23373. if (!predicate(mesh)) {
  23374. continue;
  23375. }
  23376. }
  23377. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  23378. continue;
  23379. }
  23380. var world = mesh.getWorldMatrix();
  23381. var ray = rayFunction(world);
  23382. var result = mesh.intersects(ray, false);
  23383. if (!result || !result.hit)
  23384. continue;
  23385. pickingInfos.push(result);
  23386. }
  23387. return pickingInfos;
  23388. };
  23389. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  23390. if (!BABYLON.PickingInfo) {
  23391. return null;
  23392. }
  23393. var pickingInfo = null;
  23394. if (!camera) {
  23395. if (!this.activeCamera) {
  23396. return null;
  23397. }
  23398. camera = this.activeCamera;
  23399. }
  23400. if (this.spriteManagers.length > 0) {
  23401. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  23402. var spriteManager = this.spriteManagers[spriteIndex];
  23403. if (!spriteManager.isPickable) {
  23404. continue;
  23405. }
  23406. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  23407. if (!result || !result.hit)
  23408. continue;
  23409. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  23410. continue;
  23411. pickingInfo = result;
  23412. if (fastCheck) {
  23413. break;
  23414. }
  23415. }
  23416. }
  23417. return pickingInfo || new BABYLON.PickingInfo();
  23418. };
  23419. /** Launch a ray to try to pick a mesh in the scene
  23420. * @param x position on screen
  23421. * @param y position on screen
  23422. * @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
  23423. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  23424. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  23425. */
  23426. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  23427. var _this = this;
  23428. if (!BABYLON.PickingInfo) {
  23429. return null;
  23430. }
  23431. return this._internalPick(function (world) {
  23432. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  23433. return _this._tempPickingRay;
  23434. }, predicate, fastCheck);
  23435. };
  23436. /** Launch a ray to try to pick a sprite in the scene
  23437. * @param x position on screen
  23438. * @param y position on screen
  23439. * @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
  23440. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  23441. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  23442. */
  23443. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  23444. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  23445. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  23446. };
  23447. /** Use the given ray to pick a mesh in the scene
  23448. * @param ray The ray to use to pick meshes
  23449. * @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
  23450. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  23451. */
  23452. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  23453. var _this = this;
  23454. return this._internalPick(function (world) {
  23455. if (!_this._pickWithRayInverseMatrix) {
  23456. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  23457. }
  23458. world.invertToRef(_this._pickWithRayInverseMatrix);
  23459. if (!_this._cachedRayForTransform) {
  23460. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  23461. }
  23462. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  23463. return _this._cachedRayForTransform;
  23464. }, predicate, fastCheck);
  23465. };
  23466. /**
  23467. * Launch a ray to try to pick a mesh in the scene
  23468. * @param x X position on screen
  23469. * @param y Y position on screen
  23470. * @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
  23471. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  23472. */
  23473. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  23474. var _this = this;
  23475. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  23476. };
  23477. /**
  23478. * Launch a ray to try to pick a mesh in the scene
  23479. * @param ray Ray to use
  23480. * @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
  23481. */
  23482. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  23483. var _this = this;
  23484. return this._internalMultiPick(function (world) {
  23485. if (!_this._pickWithRayInverseMatrix) {
  23486. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  23487. }
  23488. world.invertToRef(_this._pickWithRayInverseMatrix);
  23489. if (!_this._cachedRayForTransform) {
  23490. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  23491. }
  23492. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  23493. return _this._cachedRayForTransform;
  23494. }, predicate);
  23495. };
  23496. Scene.prototype.setPointerOverMesh = function (mesh) {
  23497. if (this._pointerOverMesh === mesh) {
  23498. return;
  23499. }
  23500. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  23501. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  23502. }
  23503. this._pointerOverMesh = mesh;
  23504. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  23505. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  23506. }
  23507. };
  23508. Scene.prototype.getPointerOverMesh = function () {
  23509. return this._pointerOverMesh;
  23510. };
  23511. Scene.prototype.setPointerOverSprite = function (sprite) {
  23512. if (this._pointerOverSprite === sprite) {
  23513. return;
  23514. }
  23515. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  23516. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  23517. }
  23518. this._pointerOverSprite = sprite;
  23519. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  23520. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  23521. }
  23522. };
  23523. Scene.prototype.getPointerOverSprite = function () {
  23524. return this._pointerOverSprite;
  23525. };
  23526. // Physics
  23527. Scene.prototype.getPhysicsEngine = function () {
  23528. return this._physicsEngine;
  23529. };
  23530. /**
  23531. * Enables physics to the current scene
  23532. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  23533. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  23534. * @return {boolean} was the physics engine initialized
  23535. */
  23536. Scene.prototype.enablePhysics = function (gravity, plugin) {
  23537. if (gravity === void 0) { gravity = null; }
  23538. if (this._physicsEngine) {
  23539. return true;
  23540. }
  23541. try {
  23542. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  23543. return true;
  23544. }
  23545. catch (e) {
  23546. BABYLON.Tools.Error(e.message);
  23547. return false;
  23548. }
  23549. };
  23550. Scene.prototype.disablePhysicsEngine = function () {
  23551. if (!this._physicsEngine) {
  23552. return;
  23553. }
  23554. this._physicsEngine.dispose();
  23555. this._physicsEngine = null;
  23556. };
  23557. Scene.prototype.isPhysicsEnabled = function () {
  23558. return this._physicsEngine !== undefined;
  23559. };
  23560. Scene.prototype.deleteCompoundImpostor = function (compound) {
  23561. var mesh = compound.parts[0].mesh;
  23562. if (mesh.physicsImpostor) {
  23563. mesh.physicsImpostor.dispose();
  23564. mesh.physicsImpostor = null;
  23565. }
  23566. };
  23567. // Misc.
  23568. Scene.prototype._rebuildGeometries = function () {
  23569. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  23570. var geometry = _a[_i];
  23571. geometry._rebuild();
  23572. }
  23573. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  23574. var mesh = _c[_b];
  23575. mesh._rebuild();
  23576. }
  23577. if (this.postProcessManager) {
  23578. this.postProcessManager._rebuild();
  23579. }
  23580. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  23581. var layer = _e[_d];
  23582. layer._rebuild();
  23583. }
  23584. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  23585. var highlightLayer = _g[_f];
  23586. highlightLayer._rebuild();
  23587. }
  23588. if (this._boundingBoxRenderer) {
  23589. this._boundingBoxRenderer._rebuild();
  23590. }
  23591. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  23592. var system = _j[_h];
  23593. system.rebuild();
  23594. }
  23595. if (this._postProcessRenderPipelineManager) {
  23596. this._postProcessRenderPipelineManager._rebuild();
  23597. }
  23598. };
  23599. Scene.prototype._rebuildTextures = function () {
  23600. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  23601. var texture = _a[_i];
  23602. texture._rebuild();
  23603. }
  23604. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  23605. };
  23606. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  23607. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  23608. if (replace === void 0) { replace = false; }
  23609. if (attachCameraControls === void 0) { attachCameraControls = false; }
  23610. // Dispose existing camera or light in replace mode.
  23611. if (replace) {
  23612. if (this.activeCamera) {
  23613. this.activeCamera.dispose();
  23614. this.activeCamera = null;
  23615. }
  23616. if (this.lights) {
  23617. for (var i = 0; i < this.lights.length; i++) {
  23618. this.lights[i].dispose();
  23619. }
  23620. }
  23621. }
  23622. // Light
  23623. if (this.lights.length === 0) {
  23624. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  23625. }
  23626. // Camera
  23627. if (!this.activeCamera) {
  23628. var worldExtends = this.getWorldExtends();
  23629. var worldSize = worldExtends.max.subtract(worldExtends.min);
  23630. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  23631. var camera;
  23632. var radius = worldSize.length() * 1.5;
  23633. if (createArcRotateCamera) {
  23634. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  23635. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  23636. arcRotateCamera.wheelPrecision = 100 / radius;
  23637. camera = arcRotateCamera;
  23638. }
  23639. else {
  23640. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  23641. freeCamera.setTarget(worldCenter);
  23642. camera = freeCamera;
  23643. }
  23644. camera.minZ = radius * 0.01;
  23645. camera.maxZ = radius * 1000;
  23646. camera.speed = radius * 0.2;
  23647. this.activeCamera = camera;
  23648. var canvas = this.getEngine().getRenderingCanvas();
  23649. if (attachCameraControls && canvas) {
  23650. camera.attachControl(canvas);
  23651. }
  23652. }
  23653. };
  23654. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  23655. if (pbr === void 0) { pbr = false; }
  23656. if (scale === void 0) { scale = 1000; }
  23657. if (blur === void 0) { blur = 0; }
  23658. if (environmentTexture) {
  23659. this.environmentTexture = environmentTexture;
  23660. }
  23661. if (!this.environmentTexture) {
  23662. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  23663. return null;
  23664. }
  23665. // Skybox
  23666. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  23667. if (pbr) {
  23668. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  23669. hdrSkyboxMaterial.backFaceCulling = false;
  23670. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  23671. if (hdrSkyboxMaterial.reflectionTexture) {
  23672. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  23673. }
  23674. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  23675. hdrSkyboxMaterial.disableLighting = true;
  23676. hdrSkyboxMaterial.twoSidedLighting = true;
  23677. hdrSkybox.infiniteDistance = true;
  23678. hdrSkybox.material = hdrSkyboxMaterial;
  23679. }
  23680. else {
  23681. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  23682. skyboxMaterial.backFaceCulling = false;
  23683. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  23684. if (skyboxMaterial.reflectionTexture) {
  23685. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  23686. }
  23687. skyboxMaterial.disableLighting = true;
  23688. hdrSkybox.infiniteDistance = true;
  23689. hdrSkybox.material = skyboxMaterial;
  23690. }
  23691. return hdrSkybox;
  23692. };
  23693. Scene.prototype.createDefaultEnvironment = function (options) {
  23694. if (BABYLON.EnvironmentHelper) {
  23695. return new BABYLON.EnvironmentHelper(options, this);
  23696. }
  23697. return null;
  23698. };
  23699. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  23700. if (webVROptions === void 0) { webVROptions = {}; }
  23701. return new BABYLON.VRExperienceHelper(this, webVROptions);
  23702. };
  23703. // Tags
  23704. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  23705. if (tagsQuery === undefined) {
  23706. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  23707. return list;
  23708. }
  23709. var listByTags = [];
  23710. forEach = forEach || (function (item) { return; });
  23711. for (var i in list) {
  23712. var item = list[i];
  23713. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  23714. listByTags.push(item);
  23715. forEach(item);
  23716. }
  23717. }
  23718. return listByTags;
  23719. };
  23720. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  23721. return this._getByTags(this.meshes, tagsQuery, forEach);
  23722. };
  23723. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  23724. return this._getByTags(this.cameras, tagsQuery, forEach);
  23725. };
  23726. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  23727. return this._getByTags(this.lights, tagsQuery, forEach);
  23728. };
  23729. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  23730. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  23731. };
  23732. /**
  23733. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23734. * This allowed control for front to back rendering or reversly depending of the special needs.
  23735. *
  23736. * @param renderingGroupId The rendering group id corresponding to its index
  23737. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23738. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23739. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23740. */
  23741. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23742. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23743. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23744. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23745. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  23746. };
  23747. /**
  23748. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23749. *
  23750. * @param renderingGroupId The rendering group id corresponding to its index
  23751. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23752. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23753. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23754. */
  23755. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23756. if (depth === void 0) { depth = true; }
  23757. if (stencil === void 0) { stencil = true; }
  23758. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  23759. };
  23760. /**
  23761. * Will flag all materials as dirty to trigger new shader compilation
  23762. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  23763. */
  23764. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  23765. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  23766. var material = _a[_i];
  23767. if (predicate && !predicate(material)) {
  23768. continue;
  23769. }
  23770. material.markAsDirty(flag);
  23771. }
  23772. };
  23773. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  23774. var _this = this;
  23775. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  23776. this._activeRequests.push(request);
  23777. request.onCompleteObservable.add(function (request) {
  23778. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  23779. });
  23780. return request;
  23781. };
  23782. /** @ignore */
  23783. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  23784. var _this = this;
  23785. return new Promise(function (resolve, reject) {
  23786. _this._loadFile(url, function (data) {
  23787. resolve(data);
  23788. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  23789. reject(exception);
  23790. });
  23791. });
  23792. };
  23793. // Statics
  23794. Scene._FOGMODE_NONE = 0;
  23795. Scene._FOGMODE_EXP = 1;
  23796. Scene._FOGMODE_EXP2 = 2;
  23797. Scene._FOGMODE_LINEAR = 3;
  23798. Scene._uniqueIdCounter = 0;
  23799. Scene.MinDeltaTime = 1.0;
  23800. Scene.MaxDeltaTime = 1000.0;
  23801. /** The distance in pixel that you have to move to prevent some events */
  23802. Scene.DragMovementThreshold = 10; // in pixels
  23803. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  23804. Scene.LongPressDelay = 500; // in milliseconds
  23805. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  23806. Scene.DoubleClickDelay = 300; // in milliseconds
  23807. /** If you need to check double click without raising a single click at first click, enable this flag */
  23808. Scene.ExclusiveDoubleClickMode = false;
  23809. return Scene;
  23810. }());
  23811. BABYLON.Scene = Scene;
  23812. })(BABYLON || (BABYLON = {}));
  23813. //# sourceMappingURL=babylon.scene.js.map
  23814. var BABYLON;
  23815. (function (BABYLON) {
  23816. /**
  23817. * Set of assets to keep when moving a scene into an asset container.
  23818. */
  23819. var KeepAssets = /** @class */ (function () {
  23820. function KeepAssets() {
  23821. /**
  23822. * Cameras to keep.
  23823. */
  23824. this.cameras = new Array();
  23825. /**
  23826. * Lights to keep.
  23827. */
  23828. this.lights = new Array();
  23829. /**
  23830. * Meshes to keep.
  23831. */
  23832. this.meshes = new Array();
  23833. /**
  23834. * Skeletons to keep.
  23835. */
  23836. this.skeletons = new Array();
  23837. /**
  23838. * ParticleSystems to keep.
  23839. */
  23840. this.particleSystems = new Array();
  23841. /**
  23842. * Animations to keep.
  23843. */
  23844. this.animations = new Array();
  23845. /**
  23846. * MultiMaterials to keep.
  23847. */
  23848. this.multiMaterials = new Array();
  23849. /**
  23850. * Materials to keep.
  23851. */
  23852. this.materials = new Array();
  23853. /**
  23854. * MorphTargetManagers to keep.
  23855. */
  23856. this.morphTargetManagers = new Array();
  23857. /**
  23858. * Geometries to keep.
  23859. */
  23860. this.geometries = new Array();
  23861. /**
  23862. * TransformNodes to keep.
  23863. */
  23864. this.transformNodes = new Array();
  23865. /**
  23866. * LensFlareSystems to keep.
  23867. */
  23868. this.lensFlareSystems = new Array();
  23869. /**
  23870. * ShadowGenerators to keep.
  23871. */
  23872. this.shadowGenerators = new Array();
  23873. /**
  23874. * ActionManagers to keep.
  23875. */
  23876. this.actionManagers = new Array();
  23877. /**
  23878. * Sounds to keep.
  23879. */
  23880. this.sounds = new Array();
  23881. }
  23882. return KeepAssets;
  23883. }());
  23884. BABYLON.KeepAssets = KeepAssets;
  23885. /**
  23886. * Container with a set of assets that can be added or removed from a scene.
  23887. */
  23888. var AssetContainer = /** @class */ (function () {
  23889. /**
  23890. * Instantiates an AssetContainer.
  23891. * @param scene The scene the AssetContainer belongs to.
  23892. */
  23893. function AssetContainer(scene) {
  23894. // Objects
  23895. /**
  23896. * Cameras populated in the container.
  23897. */
  23898. this.cameras = new Array();
  23899. /**
  23900. * Lights populated in the container.
  23901. */
  23902. this.lights = new Array();
  23903. /**
  23904. * Meshes populated in the container.
  23905. */
  23906. this.meshes = new Array();
  23907. /**
  23908. * Skeletons populated in the container.
  23909. */
  23910. this.skeletons = new Array();
  23911. /**
  23912. * ParticleSystems populated in the container.
  23913. */
  23914. this.particleSystems = new Array();
  23915. /**
  23916. * Animations populated in the container.
  23917. */
  23918. this.animations = new Array();
  23919. /**
  23920. * MultiMaterials populated in the container.
  23921. */
  23922. this.multiMaterials = new Array();
  23923. /**
  23924. * Materials populated in the container.
  23925. */
  23926. this.materials = new Array();
  23927. /**
  23928. * MorphTargetManagers populated in the container.
  23929. */
  23930. this.morphTargetManagers = new Array();
  23931. /**
  23932. * Geometries populated in the container.
  23933. */
  23934. this.geometries = new Array();
  23935. /**
  23936. * TransformNodes populated in the container.
  23937. */
  23938. this.transformNodes = new Array();
  23939. /**
  23940. * LensFlareSystems populated in the container.
  23941. */
  23942. this.lensFlareSystems = new Array();
  23943. /**
  23944. * ShadowGenerators populated in the container.
  23945. */
  23946. this.shadowGenerators = new Array();
  23947. /**
  23948. * ActionManagers populated in the container.
  23949. */
  23950. this.actionManagers = new Array();
  23951. /**
  23952. * Sounds populated in the container.
  23953. */
  23954. this.sounds = new Array();
  23955. this.scene = scene;
  23956. }
  23957. /**
  23958. * Adds all the assets from the container to the scene.
  23959. */
  23960. AssetContainer.prototype.addAllToScene = function () {
  23961. var _this = this;
  23962. this.cameras.forEach(function (o) {
  23963. _this.scene.addCamera(o);
  23964. });
  23965. this.lights.forEach(function (o) {
  23966. _this.scene.addLight(o);
  23967. });
  23968. this.meshes.forEach(function (o) {
  23969. _this.scene.addMesh(o);
  23970. });
  23971. this.skeletons.forEach(function (o) {
  23972. _this.scene.addSkeleton(o);
  23973. });
  23974. this.particleSystems.forEach(function (o) {
  23975. _this.scene.addParticleSystem(o);
  23976. });
  23977. this.animations.forEach(function (o) {
  23978. _this.scene.addAnimation(o);
  23979. });
  23980. this.multiMaterials.forEach(function (o) {
  23981. _this.scene.addMultiMaterial(o);
  23982. });
  23983. this.materials.forEach(function (o) {
  23984. _this.scene.addMaterial(o);
  23985. });
  23986. this.morphTargetManagers.forEach(function (o) {
  23987. _this.scene.addMorphTargetManager(o);
  23988. });
  23989. this.geometries.forEach(function (o) {
  23990. _this.scene.addGeometry(o);
  23991. });
  23992. this.transformNodes.forEach(function (o) {
  23993. _this.scene.addTransformNode(o);
  23994. });
  23995. this.lensFlareSystems.forEach(function (o) {
  23996. _this.scene.addLensFlareSystem(o);
  23997. });
  23998. this.actionManagers.forEach(function (o) {
  23999. _this.scene.addActionManager(o);
  24000. });
  24001. this.sounds.forEach(function (o) {
  24002. o.play();
  24003. o.autoplay = true;
  24004. _this.scene.mainSoundTrack.AddSound(o);
  24005. });
  24006. };
  24007. /**
  24008. * Removes all the assets in the container from the scene
  24009. */
  24010. AssetContainer.prototype.removeAllFromScene = function () {
  24011. var _this = this;
  24012. this.cameras.forEach(function (o) {
  24013. _this.scene.removeCamera(o);
  24014. });
  24015. this.lights.forEach(function (o) {
  24016. _this.scene.removeLight(o);
  24017. });
  24018. this.meshes.forEach(function (o) {
  24019. _this.scene.removeMesh(o);
  24020. });
  24021. this.skeletons.forEach(function (o) {
  24022. _this.scene.removeSkeleton(o);
  24023. });
  24024. this.particleSystems.forEach(function (o) {
  24025. _this.scene.removeParticleSystem(o);
  24026. });
  24027. this.animations.forEach(function (o) {
  24028. _this.scene.removeAnimation(o);
  24029. });
  24030. this.multiMaterials.forEach(function (o) {
  24031. _this.scene.removeMultiMaterial(o);
  24032. });
  24033. this.materials.forEach(function (o) {
  24034. _this.scene.removeMaterial(o);
  24035. });
  24036. this.morphTargetManagers.forEach(function (o) {
  24037. _this.scene.removeMorphTargetManager(o);
  24038. });
  24039. this.geometries.forEach(function (o) {
  24040. _this.scene.removeGeometry(o);
  24041. });
  24042. this.transformNodes.forEach(function (o) {
  24043. _this.scene.removeTransformNode(o);
  24044. });
  24045. this.lensFlareSystems.forEach(function (o) {
  24046. _this.scene.removeLensFlareSystem(o);
  24047. });
  24048. this.actionManagers.forEach(function (o) {
  24049. _this.scene.removeActionManager(o);
  24050. });
  24051. this.sounds.forEach(function (o) {
  24052. o.stop();
  24053. o.autoplay = false;
  24054. _this.scene.mainSoundTrack.RemoveSound(o);
  24055. });
  24056. };
  24057. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  24058. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  24059. var asset = sourceAssets_1[_i];
  24060. var move = true;
  24061. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  24062. var keepAsset = keepAssets_1[_a];
  24063. if (asset === keepAsset) {
  24064. move = false;
  24065. break;
  24066. }
  24067. }
  24068. if (move) {
  24069. targetAssets.push(asset);
  24070. }
  24071. }
  24072. };
  24073. /**
  24074. * Removes all the assets contained in the scene and adds them to the container.
  24075. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  24076. */
  24077. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  24078. if (keepAssets === undefined) {
  24079. keepAssets = new KeepAssets();
  24080. }
  24081. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  24082. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  24083. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  24084. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  24085. Array.prototype.push.apply(this.actionManagers, this.scene._actionManagers);
  24086. Array.prototype.push.apply(this.animations, this.scene.animations);
  24087. Array.prototype.push.apply(this.lensFlareSystems, this.scene.lensFlareSystems);
  24088. Array.prototype.push.apply(this.lights, this.scene.lights);
  24089. Array.prototype.push.apply(this.morphTargetManagers, this.scene.morphTargetManagers);
  24090. Array.prototype.push.apply(this.multiMaterials, this.scene.multiMaterials);
  24091. Array.prototype.push.apply(this.skeletons, this.scene.skeletons);
  24092. Array.prototype.push.apply(this.particleSystems, this.scene.particleSystems);
  24093. Array.prototype.push.apply(this.sounds, this.scene.mainSoundTrack.soundCollection);
  24094. Array.prototype.push.apply(this.transformNodes, this.scene.transformNodes);
  24095. this.removeAllFromScene();
  24096. };
  24097. return AssetContainer;
  24098. }());
  24099. BABYLON.AssetContainer = AssetContainer;
  24100. })(BABYLON || (BABYLON = {}));
  24101. //# sourceMappingURL=babylon.assetContainer.js.map
  24102. var BABYLON;
  24103. (function (BABYLON) {
  24104. var Buffer = /** @class */ (function () {
  24105. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  24106. if (instanced === void 0) { instanced = false; }
  24107. if (engine instanceof BABYLON.Mesh) {
  24108. this._engine = engine.getScene().getEngine();
  24109. }
  24110. else {
  24111. this._engine = engine;
  24112. }
  24113. this._updatable = updatable;
  24114. this._data = data;
  24115. this._strideSize = stride;
  24116. if (!postponeInternalCreation) {
  24117. this.create();
  24118. }
  24119. this._instanced = instanced;
  24120. this._instanceDivisor = instanced ? 1 : 0;
  24121. }
  24122. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  24123. // a lot of these parameters are ignored as they are overriden by the buffer
  24124. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  24125. };
  24126. // Properties
  24127. Buffer.prototype.isUpdatable = function () {
  24128. return this._updatable;
  24129. };
  24130. Buffer.prototype.getData = function () {
  24131. return this._data;
  24132. };
  24133. Buffer.prototype.getBuffer = function () {
  24134. return this._buffer;
  24135. };
  24136. Buffer.prototype.getStrideSize = function () {
  24137. return this._strideSize;
  24138. };
  24139. Buffer.prototype.getIsInstanced = function () {
  24140. return this._instanced;
  24141. };
  24142. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  24143. get: function () {
  24144. return this._instanceDivisor;
  24145. },
  24146. set: function (value) {
  24147. this._instanceDivisor = value;
  24148. if (value == 0) {
  24149. this._instanced = false;
  24150. }
  24151. else {
  24152. this._instanced = true;
  24153. }
  24154. },
  24155. enumerable: true,
  24156. configurable: true
  24157. });
  24158. // Methods
  24159. Buffer.prototype.create = function (data) {
  24160. if (data === void 0) { data = null; }
  24161. if (!data && this._buffer) {
  24162. return; // nothing to do
  24163. }
  24164. data = data || this._data;
  24165. if (!data) {
  24166. return;
  24167. }
  24168. if (!this._buffer) {
  24169. if (this._updatable) {
  24170. this._buffer = this._engine.createDynamicVertexBuffer(data);
  24171. this._data = data;
  24172. }
  24173. else {
  24174. this._buffer = this._engine.createVertexBuffer(data);
  24175. }
  24176. }
  24177. else if (this._updatable) {
  24178. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  24179. this._data = data;
  24180. }
  24181. };
  24182. Buffer.prototype._rebuild = function () {
  24183. this._buffer = null;
  24184. this.create(this._data);
  24185. };
  24186. Buffer.prototype.update = function (data) {
  24187. this.create(data);
  24188. };
  24189. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  24190. if (!this._buffer) {
  24191. return;
  24192. }
  24193. if (this._updatable) {
  24194. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  24195. this._data = null;
  24196. }
  24197. };
  24198. Buffer.prototype.dispose = function () {
  24199. if (!this._buffer) {
  24200. return;
  24201. }
  24202. if (this._engine._releaseBuffer(this._buffer)) {
  24203. this._buffer = null;
  24204. }
  24205. };
  24206. return Buffer;
  24207. }());
  24208. BABYLON.Buffer = Buffer;
  24209. })(BABYLON || (BABYLON = {}));
  24210. //# sourceMappingURL=babylon.buffer.js.map
  24211. var BABYLON;
  24212. (function (BABYLON) {
  24213. var VertexBuffer = /** @class */ (function () {
  24214. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  24215. if (!stride) {
  24216. // Deduce stride from kind
  24217. switch (kind) {
  24218. case VertexBuffer.PositionKind:
  24219. stride = 3;
  24220. break;
  24221. case VertexBuffer.NormalKind:
  24222. stride = 3;
  24223. break;
  24224. case VertexBuffer.UVKind:
  24225. case VertexBuffer.UV2Kind:
  24226. case VertexBuffer.UV3Kind:
  24227. case VertexBuffer.UV4Kind:
  24228. case VertexBuffer.UV5Kind:
  24229. case VertexBuffer.UV6Kind:
  24230. stride = 2;
  24231. break;
  24232. case VertexBuffer.TangentKind:
  24233. case VertexBuffer.ColorKind:
  24234. stride = 4;
  24235. break;
  24236. case VertexBuffer.MatricesIndicesKind:
  24237. case VertexBuffer.MatricesIndicesExtraKind:
  24238. stride = 4;
  24239. break;
  24240. case VertexBuffer.MatricesWeightsKind:
  24241. case VertexBuffer.MatricesWeightsExtraKind:
  24242. default:
  24243. stride = 4;
  24244. break;
  24245. }
  24246. }
  24247. if (data instanceof BABYLON.Buffer) {
  24248. if (!stride) {
  24249. stride = data.getStrideSize();
  24250. }
  24251. this._buffer = data;
  24252. this._ownsBuffer = false;
  24253. }
  24254. else {
  24255. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  24256. this._ownsBuffer = true;
  24257. }
  24258. this._stride = stride;
  24259. this._offset = offset ? offset : 0;
  24260. this._size = size ? size : stride;
  24261. this._kind = kind;
  24262. }
  24263. VertexBuffer.prototype._rebuild = function () {
  24264. if (!this._buffer) {
  24265. return;
  24266. }
  24267. this._buffer._rebuild();
  24268. };
  24269. /**
  24270. * Returns the kind of the VertexBuffer (string).
  24271. */
  24272. VertexBuffer.prototype.getKind = function () {
  24273. return this._kind;
  24274. };
  24275. // Properties
  24276. /**
  24277. * Boolean : is the VertexBuffer updatable ?
  24278. */
  24279. VertexBuffer.prototype.isUpdatable = function () {
  24280. return this._buffer.isUpdatable();
  24281. };
  24282. /**
  24283. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  24284. */
  24285. VertexBuffer.prototype.getData = function () {
  24286. return this._buffer.getData();
  24287. };
  24288. /**
  24289. * Returns the WebGLBuffer associated to the VertexBuffer.
  24290. */
  24291. VertexBuffer.prototype.getBuffer = function () {
  24292. return this._buffer.getBuffer();
  24293. };
  24294. /**
  24295. * Returns the stride of the VertexBuffer (integer).
  24296. */
  24297. VertexBuffer.prototype.getStrideSize = function () {
  24298. return this._stride;
  24299. };
  24300. /**
  24301. * Returns the offset (integer).
  24302. */
  24303. VertexBuffer.prototype.getOffset = function () {
  24304. return this._offset;
  24305. };
  24306. /**
  24307. * Returns the VertexBuffer total size (integer).
  24308. */
  24309. VertexBuffer.prototype.getSize = function () {
  24310. return this._size;
  24311. };
  24312. /**
  24313. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  24314. */
  24315. VertexBuffer.prototype.getIsInstanced = function () {
  24316. return this._buffer.getIsInstanced();
  24317. };
  24318. /**
  24319. * Returns the instancing divisor, zero for non-instanced (integer).
  24320. */
  24321. VertexBuffer.prototype.getInstanceDivisor = function () {
  24322. return this._buffer.instanceDivisor;
  24323. };
  24324. // Methods
  24325. /**
  24326. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  24327. * Returns the created WebGLBuffer.
  24328. */
  24329. VertexBuffer.prototype.create = function (data) {
  24330. return this._buffer.create(data);
  24331. };
  24332. /**
  24333. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  24334. * This function will create a new buffer if the current one is not updatable
  24335. * Returns the updated WebGLBuffer.
  24336. */
  24337. VertexBuffer.prototype.update = function (data) {
  24338. return this._buffer.update(data);
  24339. };
  24340. /**
  24341. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  24342. * Returns the directly updated WebGLBuffer.
  24343. */
  24344. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  24345. return this._buffer.updateDirectly(data, offset);
  24346. };
  24347. /**
  24348. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  24349. */
  24350. VertexBuffer.prototype.dispose = function () {
  24351. if (this._ownsBuffer) {
  24352. this._buffer.dispose();
  24353. }
  24354. };
  24355. Object.defineProperty(VertexBuffer, "PositionKind", {
  24356. get: function () {
  24357. return VertexBuffer._PositionKind;
  24358. },
  24359. enumerable: true,
  24360. configurable: true
  24361. });
  24362. Object.defineProperty(VertexBuffer, "NormalKind", {
  24363. get: function () {
  24364. return VertexBuffer._NormalKind;
  24365. },
  24366. enumerable: true,
  24367. configurable: true
  24368. });
  24369. Object.defineProperty(VertexBuffer, "TangentKind", {
  24370. get: function () {
  24371. return VertexBuffer._TangentKind;
  24372. },
  24373. enumerable: true,
  24374. configurable: true
  24375. });
  24376. Object.defineProperty(VertexBuffer, "UVKind", {
  24377. get: function () {
  24378. return VertexBuffer._UVKind;
  24379. },
  24380. enumerable: true,
  24381. configurable: true
  24382. });
  24383. Object.defineProperty(VertexBuffer, "UV2Kind", {
  24384. get: function () {
  24385. return VertexBuffer._UV2Kind;
  24386. },
  24387. enumerable: true,
  24388. configurable: true
  24389. });
  24390. Object.defineProperty(VertexBuffer, "UV3Kind", {
  24391. get: function () {
  24392. return VertexBuffer._UV3Kind;
  24393. },
  24394. enumerable: true,
  24395. configurable: true
  24396. });
  24397. Object.defineProperty(VertexBuffer, "UV4Kind", {
  24398. get: function () {
  24399. return VertexBuffer._UV4Kind;
  24400. },
  24401. enumerable: true,
  24402. configurable: true
  24403. });
  24404. Object.defineProperty(VertexBuffer, "UV5Kind", {
  24405. get: function () {
  24406. return VertexBuffer._UV5Kind;
  24407. },
  24408. enumerable: true,
  24409. configurable: true
  24410. });
  24411. Object.defineProperty(VertexBuffer, "UV6Kind", {
  24412. get: function () {
  24413. return VertexBuffer._UV6Kind;
  24414. },
  24415. enumerable: true,
  24416. configurable: true
  24417. });
  24418. Object.defineProperty(VertexBuffer, "ColorKind", {
  24419. get: function () {
  24420. return VertexBuffer._ColorKind;
  24421. },
  24422. enumerable: true,
  24423. configurable: true
  24424. });
  24425. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  24426. get: function () {
  24427. return VertexBuffer._MatricesIndicesKind;
  24428. },
  24429. enumerable: true,
  24430. configurable: true
  24431. });
  24432. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  24433. get: function () {
  24434. return VertexBuffer._MatricesWeightsKind;
  24435. },
  24436. enumerable: true,
  24437. configurable: true
  24438. });
  24439. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  24440. get: function () {
  24441. return VertexBuffer._MatricesIndicesExtraKind;
  24442. },
  24443. enumerable: true,
  24444. configurable: true
  24445. });
  24446. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  24447. get: function () {
  24448. return VertexBuffer._MatricesWeightsExtraKind;
  24449. },
  24450. enumerable: true,
  24451. configurable: true
  24452. });
  24453. // Enums
  24454. VertexBuffer._PositionKind = "position";
  24455. VertexBuffer._NormalKind = "normal";
  24456. VertexBuffer._TangentKind = "tangent";
  24457. VertexBuffer._UVKind = "uv";
  24458. VertexBuffer._UV2Kind = "uv2";
  24459. VertexBuffer._UV3Kind = "uv3";
  24460. VertexBuffer._UV4Kind = "uv4";
  24461. VertexBuffer._UV5Kind = "uv5";
  24462. VertexBuffer._UV6Kind = "uv6";
  24463. VertexBuffer._ColorKind = "color";
  24464. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  24465. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  24466. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  24467. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  24468. return VertexBuffer;
  24469. }());
  24470. BABYLON.VertexBuffer = VertexBuffer;
  24471. })(BABYLON || (BABYLON = {}));
  24472. //# sourceMappingURL=babylon.vertexBuffer.js.map
  24473. var BABYLON;
  24474. (function (BABYLON) {
  24475. /**
  24476. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  24477. */
  24478. var DummyInternalTextureTracker = /** @class */ (function () {
  24479. function DummyInternalTextureTracker() {
  24480. /**
  24481. * Gets or set the previous tracker in the list
  24482. */
  24483. this.previous = null;
  24484. /**
  24485. * Gets or set the next tracker in the list
  24486. */
  24487. this.next = null;
  24488. }
  24489. return DummyInternalTextureTracker;
  24490. }());
  24491. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  24492. })(BABYLON || (BABYLON = {}));
  24493. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  24494. var BABYLON;
  24495. (function (BABYLON) {
  24496. /**
  24497. * Class used to store data associated with WebGL texture data for the engine
  24498. * This class should not be used directly
  24499. */
  24500. var InternalTexture = /** @class */ (function () {
  24501. /**
  24502. * Creates a new InternalTexture
  24503. * @param engine defines the engine to use
  24504. * @param dataSource defines the type of data that will be used
  24505. */
  24506. function InternalTexture(engine, dataSource) {
  24507. /**
  24508. * Observable called when the texture is loaded
  24509. */
  24510. this.onLoadedObservable = new BABYLON.Observable();
  24511. /**
  24512. * Gets or set the previous tracker in the list
  24513. */
  24514. this.previous = null;
  24515. /**
  24516. * Gets or set the next tracker in the list
  24517. */
  24518. this.next = null;
  24519. // Private
  24520. /** @ignore */
  24521. this._initialSlot = -1;
  24522. /** @ignore */
  24523. this._designatedSlot = -1;
  24524. /** @ignore */
  24525. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  24526. /** @ignore */
  24527. this._references = 1;
  24528. this._engine = engine;
  24529. this._dataSource = dataSource;
  24530. this._webGLTexture = engine._createTexture();
  24531. }
  24532. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  24533. /**
  24534. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  24535. */
  24536. get: function () {
  24537. return this._dataSource;
  24538. },
  24539. enumerable: true,
  24540. configurable: true
  24541. });
  24542. /**
  24543. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  24544. */
  24545. InternalTexture.prototype.incrementReferences = function () {
  24546. this._references++;
  24547. };
  24548. /**
  24549. * Change the size of the texture (not the size of the content)
  24550. * @param width defines the new width
  24551. * @param height defines the new height
  24552. * @param depth defines the new depth (1 by default)
  24553. */
  24554. InternalTexture.prototype.updateSize = function (width, height, depth) {
  24555. if (depth === void 0) { depth = 1; }
  24556. this.width = width;
  24557. this.height = height;
  24558. this.depth = depth;
  24559. this.baseWidth = width;
  24560. this.baseHeight = height;
  24561. this.baseDepth = depth;
  24562. this._size = width * height * depth;
  24563. };
  24564. /** @ignore */
  24565. InternalTexture.prototype._rebuild = function () {
  24566. var _this = this;
  24567. var proxy;
  24568. this.isReady = false;
  24569. this._cachedCoordinatesMode = null;
  24570. this._cachedWrapU = null;
  24571. this._cachedWrapV = null;
  24572. this._cachedAnisotropicFilteringLevel = null;
  24573. switch (this._dataSource) {
  24574. case InternalTexture.DATASOURCE_TEMP:
  24575. return;
  24576. case InternalTexture.DATASOURCE_URL:
  24577. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  24578. _this.isReady = true;
  24579. }, null, this._buffer, undefined, this.format);
  24580. proxy._swapAndDie(this);
  24581. return;
  24582. case InternalTexture.DATASOURCE_RAW:
  24583. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  24584. proxy._swapAndDie(this);
  24585. this.isReady = true;
  24586. return;
  24587. case InternalTexture.DATASOURCE_RAW3D:
  24588. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  24589. proxy._swapAndDie(this);
  24590. this.isReady = true;
  24591. return;
  24592. case InternalTexture.DATASOURCE_DYNAMIC:
  24593. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  24594. proxy._swapAndDie(this);
  24595. // The engine will make sure to update content so no need to flag it as isReady = true
  24596. return;
  24597. case InternalTexture.DATASOURCE_RENDERTARGET:
  24598. var options = new BABYLON.RenderTargetCreationOptions();
  24599. options.generateDepthBuffer = this._generateDepthBuffer;
  24600. options.generateMipMaps = this.generateMipMaps;
  24601. options.generateStencilBuffer = this._generateStencilBuffer;
  24602. options.samplingMode = this.samplingMode;
  24603. options.type = this.type;
  24604. if (this.isCube) {
  24605. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  24606. }
  24607. else {
  24608. var size = {
  24609. width: this.width,
  24610. height: this.height
  24611. };
  24612. proxy = this._engine.createRenderTargetTexture(size, options);
  24613. }
  24614. proxy._swapAndDie(this);
  24615. this.isReady = true;
  24616. return;
  24617. case InternalTexture.DATASOURCE_CUBE:
  24618. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  24619. _this.isReady = true;
  24620. }, null, this.format, this._extension);
  24621. proxy._swapAndDie(this);
  24622. return;
  24623. case InternalTexture.DATASOURCE_CUBERAW:
  24624. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  24625. proxy._swapAndDie(this);
  24626. this.isReady = true;
  24627. return;
  24628. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  24629. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  24630. if (proxy) {
  24631. proxy._swapAndDie(_this);
  24632. }
  24633. _this.isReady = true;
  24634. }, null, this.format, this._extension);
  24635. return;
  24636. }
  24637. };
  24638. InternalTexture.prototype._swapAndDie = function (target) {
  24639. target._webGLTexture = this._webGLTexture;
  24640. if (this._framebuffer) {
  24641. target._framebuffer = this._framebuffer;
  24642. }
  24643. if (this._depthStencilBuffer) {
  24644. target._depthStencilBuffer = this._depthStencilBuffer;
  24645. }
  24646. if (this._lodTextureHigh) {
  24647. if (target._lodTextureHigh) {
  24648. target._lodTextureHigh.dispose();
  24649. }
  24650. target._lodTextureHigh = this._lodTextureHigh;
  24651. }
  24652. if (this._lodTextureMid) {
  24653. if (target._lodTextureMid) {
  24654. target._lodTextureMid.dispose();
  24655. }
  24656. target._lodTextureMid = this._lodTextureMid;
  24657. }
  24658. if (this._lodTextureLow) {
  24659. if (target._lodTextureLow) {
  24660. target._lodTextureLow.dispose();
  24661. }
  24662. target._lodTextureLow = this._lodTextureLow;
  24663. }
  24664. var cache = this._engine.getLoadedTexturesCache();
  24665. var index = cache.indexOf(this);
  24666. if (index !== -1) {
  24667. cache.splice(index, 1);
  24668. }
  24669. };
  24670. /**
  24671. * Dispose the current allocated resources
  24672. */
  24673. InternalTexture.prototype.dispose = function () {
  24674. if (!this._webGLTexture) {
  24675. return;
  24676. }
  24677. this._references--;
  24678. if (this._references === 0) {
  24679. this._engine._releaseTexture(this);
  24680. this._webGLTexture = null;
  24681. this.previous = null;
  24682. this.next = null;
  24683. }
  24684. };
  24685. /**
  24686. * The source of the texture data is unknown
  24687. */
  24688. InternalTexture.DATASOURCE_UNKNOWN = 0;
  24689. /**
  24690. * Texture data comes from an URL
  24691. */
  24692. InternalTexture.DATASOURCE_URL = 1;
  24693. /**
  24694. * Texture data is only used for temporary storage
  24695. */
  24696. InternalTexture.DATASOURCE_TEMP = 2;
  24697. /**
  24698. * Texture data comes from raw data (ArrayBuffer)
  24699. */
  24700. InternalTexture.DATASOURCE_RAW = 3;
  24701. /**
  24702. * Texture content is dynamic (video or dynamic texture)
  24703. */
  24704. InternalTexture.DATASOURCE_DYNAMIC = 4;
  24705. /**
  24706. * Texture content is generated by rendering to it
  24707. */
  24708. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  24709. /**
  24710. * Texture content is part of a multi render target process
  24711. */
  24712. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  24713. /**
  24714. * Texture data comes from a cube data file
  24715. */
  24716. InternalTexture.DATASOURCE_CUBE = 7;
  24717. /**
  24718. * Texture data comes from a raw cube data
  24719. */
  24720. InternalTexture.DATASOURCE_CUBERAW = 8;
  24721. /**
  24722. * Texture data come from a prefiltered cube data file
  24723. */
  24724. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  24725. /**
  24726. * Texture content is raw 3D data
  24727. */
  24728. InternalTexture.DATASOURCE_RAW3D = 10;
  24729. return InternalTexture;
  24730. }());
  24731. BABYLON.InternalTexture = InternalTexture;
  24732. })(BABYLON || (BABYLON = {}));
  24733. //# sourceMappingURL=babylon.internalTexture.js.map
  24734. var BABYLON;
  24735. (function (BABYLON) {
  24736. var BaseTexture = /** @class */ (function () {
  24737. function BaseTexture(scene) {
  24738. this._hasAlpha = false;
  24739. this.getAlphaFromRGB = false;
  24740. this.level = 1;
  24741. this.coordinatesIndex = 0;
  24742. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  24743. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  24744. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  24745. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  24746. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  24747. this.isCube = false;
  24748. this.is3D = false;
  24749. this.gammaSpace = true;
  24750. this.invertZ = false;
  24751. this.lodLevelInAlpha = false;
  24752. this.lodGenerationOffset = 0.0;
  24753. this.lodGenerationScale = 0.8;
  24754. this.isRenderTarget = false;
  24755. this.animations = new Array();
  24756. /**
  24757. * An event triggered when the texture is disposed.
  24758. * @type {BABYLON.Observable}
  24759. */
  24760. this.onDisposeObservable = new BABYLON.Observable();
  24761. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  24762. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  24763. if (this._scene) {
  24764. this._scene.textures.push(this);
  24765. }
  24766. this._uid = null;
  24767. }
  24768. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  24769. get: function () {
  24770. return this._hasAlpha;
  24771. },
  24772. set: function (value) {
  24773. if (this._hasAlpha === value) {
  24774. return;
  24775. }
  24776. this._hasAlpha = value;
  24777. if (this._scene) {
  24778. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  24779. }
  24780. },
  24781. enumerable: true,
  24782. configurable: true
  24783. });
  24784. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  24785. get: function () {
  24786. return this._coordinatesMode;
  24787. },
  24788. set: function (value) {
  24789. if (this._coordinatesMode === value) {
  24790. return;
  24791. }
  24792. this._coordinatesMode = value;
  24793. if (this._scene) {
  24794. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24795. }
  24796. },
  24797. enumerable: true,
  24798. configurable: true
  24799. });
  24800. Object.defineProperty(BaseTexture.prototype, "uid", {
  24801. get: function () {
  24802. if (!this._uid) {
  24803. this._uid = BABYLON.Tools.RandomId();
  24804. }
  24805. return this._uid;
  24806. },
  24807. enumerable: true,
  24808. configurable: true
  24809. });
  24810. BaseTexture.prototype.toString = function () {
  24811. return this.name;
  24812. };
  24813. BaseTexture.prototype.getClassName = function () {
  24814. return "BaseTexture";
  24815. };
  24816. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  24817. set: function (callback) {
  24818. if (this._onDisposeObserver) {
  24819. this.onDisposeObservable.remove(this._onDisposeObserver);
  24820. }
  24821. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24822. },
  24823. enumerable: true,
  24824. configurable: true
  24825. });
  24826. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  24827. get: function () {
  24828. return true;
  24829. },
  24830. enumerable: true,
  24831. configurable: true
  24832. });
  24833. BaseTexture.prototype.getScene = function () {
  24834. return this._scene;
  24835. };
  24836. BaseTexture.prototype.getTextureMatrix = function () {
  24837. return BABYLON.Matrix.IdentityReadOnly;
  24838. };
  24839. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  24840. return BABYLON.Matrix.IdentityReadOnly;
  24841. };
  24842. BaseTexture.prototype.getInternalTexture = function () {
  24843. return this._texture;
  24844. };
  24845. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  24846. return !this.isBlocking || this.isReady();
  24847. };
  24848. BaseTexture.prototype.isReady = function () {
  24849. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  24850. this.delayLoad();
  24851. return false;
  24852. }
  24853. if (this._texture) {
  24854. return this._texture.isReady;
  24855. }
  24856. return false;
  24857. };
  24858. BaseTexture.prototype.getSize = function () {
  24859. if (this._texture && this._texture.width) {
  24860. return new BABYLON.Size(this._texture.width, this._texture.height);
  24861. }
  24862. if (this._texture && this._texture._size) {
  24863. return new BABYLON.Size(this._texture._size, this._texture._size);
  24864. }
  24865. return BABYLON.Size.Zero();
  24866. };
  24867. BaseTexture.prototype.getBaseSize = function () {
  24868. if (!this.isReady() || !this._texture)
  24869. return BABYLON.Size.Zero();
  24870. if (this._texture._size) {
  24871. return new BABYLON.Size(this._texture._size, this._texture._size);
  24872. }
  24873. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  24874. };
  24875. BaseTexture.prototype.scale = function (ratio) {
  24876. };
  24877. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  24878. get: function () {
  24879. return false;
  24880. },
  24881. enumerable: true,
  24882. configurable: true
  24883. });
  24884. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  24885. if (!this._scene) {
  24886. return null;
  24887. }
  24888. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  24889. for (var index = 0; index < texturesCache.length; index++) {
  24890. var texturesCacheEntry = texturesCache[index];
  24891. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  24892. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  24893. texturesCacheEntry.incrementReferences();
  24894. return texturesCacheEntry;
  24895. }
  24896. }
  24897. }
  24898. return null;
  24899. };
  24900. BaseTexture.prototype._rebuild = function () {
  24901. };
  24902. BaseTexture.prototype.delayLoad = function () {
  24903. };
  24904. BaseTexture.prototype.clone = function () {
  24905. return null;
  24906. };
  24907. Object.defineProperty(BaseTexture.prototype, "textureType", {
  24908. get: function () {
  24909. if (!this._texture) {
  24910. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  24911. }
  24912. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  24913. },
  24914. enumerable: true,
  24915. configurable: true
  24916. });
  24917. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  24918. get: function () {
  24919. if (!this._texture) {
  24920. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  24921. }
  24922. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  24923. },
  24924. enumerable: true,
  24925. configurable: true
  24926. });
  24927. BaseTexture.prototype.readPixels = function (faceIndex) {
  24928. if (faceIndex === void 0) { faceIndex = 0; }
  24929. if (!this._texture) {
  24930. return null;
  24931. }
  24932. var size = this.getSize();
  24933. var scene = this.getScene();
  24934. if (!scene) {
  24935. return null;
  24936. }
  24937. var engine = scene.getEngine();
  24938. if (this._texture.isCube) {
  24939. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  24940. }
  24941. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  24942. };
  24943. BaseTexture.prototype.releaseInternalTexture = function () {
  24944. if (this._texture) {
  24945. this._texture.dispose();
  24946. this._texture = null;
  24947. }
  24948. };
  24949. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  24950. get: function () {
  24951. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  24952. return null;
  24953. }
  24954. if (!this._texture._sphericalPolynomial) {
  24955. this._texture._sphericalPolynomial =
  24956. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  24957. }
  24958. return this._texture._sphericalPolynomial;
  24959. },
  24960. set: function (value) {
  24961. if (this._texture) {
  24962. this._texture._sphericalPolynomial = value;
  24963. }
  24964. },
  24965. enumerable: true,
  24966. configurable: true
  24967. });
  24968. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  24969. get: function () {
  24970. if (this._texture) {
  24971. return this._texture._lodTextureHigh;
  24972. }
  24973. return null;
  24974. },
  24975. enumerable: true,
  24976. configurable: true
  24977. });
  24978. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  24979. get: function () {
  24980. if (this._texture) {
  24981. return this._texture._lodTextureMid;
  24982. }
  24983. return null;
  24984. },
  24985. enumerable: true,
  24986. configurable: true
  24987. });
  24988. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  24989. get: function () {
  24990. if (this._texture) {
  24991. return this._texture._lodTextureLow;
  24992. }
  24993. return null;
  24994. },
  24995. enumerable: true,
  24996. configurable: true
  24997. });
  24998. BaseTexture.prototype.dispose = function () {
  24999. if (!this._scene) {
  25000. return;
  25001. }
  25002. // Animations
  25003. this._scene.stopAnimation(this);
  25004. // Remove from scene
  25005. this._scene._removePendingData(this);
  25006. var index = this._scene.textures.indexOf(this);
  25007. if (index >= 0) {
  25008. this._scene.textures.splice(index, 1);
  25009. }
  25010. if (this._texture === undefined) {
  25011. return;
  25012. }
  25013. // Release
  25014. this.releaseInternalTexture();
  25015. // Callback
  25016. this.onDisposeObservable.notifyObservers(this);
  25017. this.onDisposeObservable.clear();
  25018. };
  25019. BaseTexture.prototype.serialize = function () {
  25020. if (!this.name) {
  25021. return null;
  25022. }
  25023. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  25024. // Animations
  25025. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  25026. return serializationObject;
  25027. };
  25028. BaseTexture.WhenAllReady = function (textures, callback) {
  25029. var numRemaining = textures.length;
  25030. if (numRemaining === 0) {
  25031. callback();
  25032. return;
  25033. }
  25034. var _loop_1 = function () {
  25035. texture = textures[i];
  25036. if (texture.isReady()) {
  25037. if (--numRemaining === 0) {
  25038. callback();
  25039. }
  25040. }
  25041. else {
  25042. onLoadObservable = texture.onLoadObservable;
  25043. var onLoadCallback_1 = function () {
  25044. onLoadObservable.removeCallback(onLoadCallback_1);
  25045. if (--numRemaining === 0) {
  25046. callback();
  25047. }
  25048. };
  25049. onLoadObservable.add(onLoadCallback_1);
  25050. }
  25051. };
  25052. var texture, onLoadObservable;
  25053. for (var i = 0; i < textures.length; i++) {
  25054. _loop_1();
  25055. }
  25056. };
  25057. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  25058. __decorate([
  25059. BABYLON.serialize()
  25060. ], BaseTexture.prototype, "name", void 0);
  25061. __decorate([
  25062. BABYLON.serialize("hasAlpha")
  25063. ], BaseTexture.prototype, "_hasAlpha", void 0);
  25064. __decorate([
  25065. BABYLON.serialize()
  25066. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  25067. __decorate([
  25068. BABYLON.serialize()
  25069. ], BaseTexture.prototype, "level", void 0);
  25070. __decorate([
  25071. BABYLON.serialize()
  25072. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  25073. __decorate([
  25074. BABYLON.serialize("coordinatesMode")
  25075. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  25076. __decorate([
  25077. BABYLON.serialize()
  25078. ], BaseTexture.prototype, "wrapU", void 0);
  25079. __decorate([
  25080. BABYLON.serialize()
  25081. ], BaseTexture.prototype, "wrapV", void 0);
  25082. __decorate([
  25083. BABYLON.serialize()
  25084. ], BaseTexture.prototype, "wrapR", void 0);
  25085. __decorate([
  25086. BABYLON.serialize()
  25087. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  25088. __decorate([
  25089. BABYLON.serialize()
  25090. ], BaseTexture.prototype, "isCube", void 0);
  25091. __decorate([
  25092. BABYLON.serialize()
  25093. ], BaseTexture.prototype, "is3D", void 0);
  25094. __decorate([
  25095. BABYLON.serialize()
  25096. ], BaseTexture.prototype, "gammaSpace", void 0);
  25097. __decorate([
  25098. BABYLON.serialize()
  25099. ], BaseTexture.prototype, "invertZ", void 0);
  25100. __decorate([
  25101. BABYLON.serialize()
  25102. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  25103. __decorate([
  25104. BABYLON.serialize()
  25105. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  25106. __decorate([
  25107. BABYLON.serialize()
  25108. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  25109. __decorate([
  25110. BABYLON.serialize()
  25111. ], BaseTexture.prototype, "isRenderTarget", void 0);
  25112. return BaseTexture;
  25113. }());
  25114. BABYLON.BaseTexture = BaseTexture;
  25115. })(BABYLON || (BABYLON = {}));
  25116. //# sourceMappingURL=babylon.baseTexture.js.map
  25117. var BABYLON;
  25118. (function (BABYLON) {
  25119. var Texture = /** @class */ (function (_super) {
  25120. __extends(Texture, _super);
  25121. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  25122. if (noMipmap === void 0) { noMipmap = false; }
  25123. if (invertY === void 0) { invertY = true; }
  25124. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  25125. if (onLoad === void 0) { onLoad = null; }
  25126. if (onError === void 0) { onError = null; }
  25127. if (buffer === void 0) { buffer = null; }
  25128. if (deleteBuffer === void 0) { deleteBuffer = false; }
  25129. var _this = _super.call(this, scene) || this;
  25130. _this.uOffset = 0;
  25131. _this.vOffset = 0;
  25132. _this.uScale = 1.0;
  25133. _this.vScale = 1.0;
  25134. _this.uAng = 0;
  25135. _this.vAng = 0;
  25136. _this.wAng = 0;
  25137. _this._isBlocking = true;
  25138. _this.name = url || "";
  25139. _this.url = url;
  25140. _this._noMipmap = noMipmap;
  25141. _this._invertY = invertY;
  25142. _this._samplingMode = samplingMode;
  25143. _this._buffer = buffer;
  25144. _this._deleteBuffer = deleteBuffer;
  25145. if (format) {
  25146. _this._format = format;
  25147. }
  25148. scene = _this.getScene();
  25149. if (!scene) {
  25150. return _this;
  25151. }
  25152. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  25153. var load = function () {
  25154. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  25155. _this.onLoadObservable.notifyObservers(_this);
  25156. }
  25157. if (onLoad) {
  25158. onLoad();
  25159. }
  25160. if (!_this.isBlocking && scene) {
  25161. scene.resetCachedMaterial();
  25162. }
  25163. };
  25164. if (!_this.url) {
  25165. _this._delayedOnLoad = load;
  25166. _this._delayedOnError = onError;
  25167. return _this;
  25168. }
  25169. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  25170. if (!_this._texture) {
  25171. if (!scene.useDelayedTextureLoading) {
  25172. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  25173. if (deleteBuffer) {
  25174. delete _this._buffer;
  25175. }
  25176. }
  25177. else {
  25178. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  25179. _this._delayedOnLoad = load;
  25180. _this._delayedOnError = onError;
  25181. }
  25182. }
  25183. else {
  25184. if (_this._texture.isReady) {
  25185. BABYLON.Tools.SetImmediate(function () { return load(); });
  25186. }
  25187. else {
  25188. _this._texture.onLoadedObservable.add(load);
  25189. }
  25190. }
  25191. return _this;
  25192. }
  25193. Object.defineProperty(Texture.prototype, "noMipmap", {
  25194. get: function () {
  25195. return this._noMipmap;
  25196. },
  25197. enumerable: true,
  25198. configurable: true
  25199. });
  25200. Object.defineProperty(Texture.prototype, "isBlocking", {
  25201. get: function () {
  25202. return this._isBlocking;
  25203. },
  25204. set: function (value) {
  25205. this._isBlocking = value;
  25206. },
  25207. enumerable: true,
  25208. configurable: true
  25209. });
  25210. Object.defineProperty(Texture.prototype, "samplingMode", {
  25211. get: function () {
  25212. return this._samplingMode;
  25213. },
  25214. enumerable: true,
  25215. configurable: true
  25216. });
  25217. Texture.prototype.updateURL = function (url) {
  25218. this.url = url;
  25219. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  25220. this.delayLoad();
  25221. };
  25222. Texture.prototype.delayLoad = function () {
  25223. var _this = this;
  25224. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  25225. return;
  25226. }
  25227. var scene = this.getScene();
  25228. if (!scene) {
  25229. return;
  25230. }
  25231. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  25232. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  25233. if (!this._texture) {
  25234. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  25235. if (this._deleteBuffer) {
  25236. delete this._buffer;
  25237. }
  25238. }
  25239. else {
  25240. if (this._texture.isReady) {
  25241. BABYLON.Tools.SetImmediate(function () {
  25242. if (!_this._delayedOnLoad) {
  25243. return;
  25244. }
  25245. _this._delayedOnLoad();
  25246. });
  25247. }
  25248. else {
  25249. if (this._delayedOnLoad) {
  25250. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  25251. }
  25252. }
  25253. }
  25254. };
  25255. Texture.prototype.updateSamplingMode = function (samplingMode) {
  25256. if (!this._texture) {
  25257. return;
  25258. }
  25259. var scene = this.getScene();
  25260. if (!scene) {
  25261. return;
  25262. }
  25263. this._samplingMode = samplingMode;
  25264. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  25265. };
  25266. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  25267. x *= this.uScale;
  25268. y *= this.vScale;
  25269. x -= 0.5 * this.uScale;
  25270. y -= 0.5 * this.vScale;
  25271. z -= 0.5;
  25272. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  25273. t.x += 0.5 * this.uScale + this.uOffset;
  25274. t.y += 0.5 * this.vScale + this.vOffset;
  25275. t.z += 0.5;
  25276. };
  25277. Texture.prototype.getTextureMatrix = function () {
  25278. var _this = this;
  25279. if (this.uOffset === this._cachedUOffset &&
  25280. this.vOffset === this._cachedVOffset &&
  25281. this.uScale === this._cachedUScale &&
  25282. this.vScale === this._cachedVScale &&
  25283. this.uAng === this._cachedUAng &&
  25284. this.vAng === this._cachedVAng &&
  25285. this.wAng === this._cachedWAng) {
  25286. return this._cachedTextureMatrix;
  25287. }
  25288. this._cachedUOffset = this.uOffset;
  25289. this._cachedVOffset = this.vOffset;
  25290. this._cachedUScale = this.uScale;
  25291. this._cachedVScale = this.vScale;
  25292. this._cachedUAng = this.uAng;
  25293. this._cachedVAng = this.vAng;
  25294. this._cachedWAng = this.wAng;
  25295. if (!this._cachedTextureMatrix) {
  25296. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  25297. this._rowGenerationMatrix = new BABYLON.Matrix();
  25298. this._t0 = BABYLON.Vector3.Zero();
  25299. this._t1 = BABYLON.Vector3.Zero();
  25300. this._t2 = BABYLON.Vector3.Zero();
  25301. }
  25302. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  25303. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  25304. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  25305. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  25306. this._t1.subtractInPlace(this._t0);
  25307. this._t2.subtractInPlace(this._t0);
  25308. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  25309. this._cachedTextureMatrix.m[0] = this._t1.x;
  25310. this._cachedTextureMatrix.m[1] = this._t1.y;
  25311. this._cachedTextureMatrix.m[2] = this._t1.z;
  25312. this._cachedTextureMatrix.m[4] = this._t2.x;
  25313. this._cachedTextureMatrix.m[5] = this._t2.y;
  25314. this._cachedTextureMatrix.m[6] = this._t2.z;
  25315. this._cachedTextureMatrix.m[8] = this._t0.x;
  25316. this._cachedTextureMatrix.m[9] = this._t0.y;
  25317. this._cachedTextureMatrix.m[10] = this._t0.z;
  25318. var scene = this.getScene();
  25319. if (!scene) {
  25320. return this._cachedTextureMatrix;
  25321. }
  25322. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  25323. return mat.hasTexture(_this);
  25324. });
  25325. return this._cachedTextureMatrix;
  25326. };
  25327. Texture.prototype.getReflectionTextureMatrix = function () {
  25328. var _this = this;
  25329. var scene = this.getScene();
  25330. if (!scene) {
  25331. return this._cachedTextureMatrix;
  25332. }
  25333. if (this.uOffset === this._cachedUOffset &&
  25334. this.vOffset === this._cachedVOffset &&
  25335. this.uScale === this._cachedUScale &&
  25336. this.vScale === this._cachedVScale &&
  25337. this.coordinatesMode === this._cachedCoordinatesMode) {
  25338. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  25339. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  25340. return this._cachedTextureMatrix;
  25341. }
  25342. }
  25343. else {
  25344. return this._cachedTextureMatrix;
  25345. }
  25346. }
  25347. if (!this._cachedTextureMatrix) {
  25348. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  25349. }
  25350. if (!this._projectionModeMatrix) {
  25351. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  25352. }
  25353. this._cachedUOffset = this.uOffset;
  25354. this._cachedVOffset = this.vOffset;
  25355. this._cachedUScale = this.uScale;
  25356. this._cachedVScale = this.vScale;
  25357. this._cachedCoordinatesMode = this.coordinatesMode;
  25358. switch (this.coordinatesMode) {
  25359. case Texture.PLANAR_MODE:
  25360. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  25361. this._cachedTextureMatrix[0] = this.uScale;
  25362. this._cachedTextureMatrix[5] = this.vScale;
  25363. this._cachedTextureMatrix[12] = this.uOffset;
  25364. this._cachedTextureMatrix[13] = this.vOffset;
  25365. break;
  25366. case Texture.PROJECTION_MODE:
  25367. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  25368. this._projectionModeMatrix.m[0] = 0.5;
  25369. this._projectionModeMatrix.m[5] = -0.5;
  25370. this._projectionModeMatrix.m[10] = 0.0;
  25371. this._projectionModeMatrix.m[12] = 0.5;
  25372. this._projectionModeMatrix.m[13] = 0.5;
  25373. this._projectionModeMatrix.m[14] = 1.0;
  25374. this._projectionModeMatrix.m[15] = 1.0;
  25375. var projectionMatrix = scene.getProjectionMatrix();
  25376. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  25377. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  25378. break;
  25379. default:
  25380. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  25381. break;
  25382. }
  25383. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  25384. return (mat.getActiveTextures().indexOf(_this) !== -1);
  25385. });
  25386. return this._cachedTextureMatrix;
  25387. };
  25388. Texture.prototype.clone = function () {
  25389. var _this = this;
  25390. return BABYLON.SerializationHelper.Clone(function () {
  25391. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  25392. }, this);
  25393. };
  25394. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  25395. get: function () {
  25396. if (!this._onLoadObservable) {
  25397. this._onLoadObservable = new BABYLON.Observable();
  25398. }
  25399. return this._onLoadObservable;
  25400. },
  25401. enumerable: true,
  25402. configurable: true
  25403. });
  25404. Texture.prototype.serialize = function () {
  25405. var serializationObject = _super.prototype.serialize.call(this);
  25406. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  25407. serializationObject.base64String = this._buffer;
  25408. serializationObject.name = serializationObject.name.replace("data:", "");
  25409. }
  25410. return serializationObject;
  25411. };
  25412. Texture.prototype.getClassName = function () {
  25413. return "Texture";
  25414. };
  25415. Texture.prototype.dispose = function () {
  25416. _super.prototype.dispose.call(this);
  25417. if (this.onLoadObservable) {
  25418. this.onLoadObservable.clear();
  25419. this._onLoadObservable = null;
  25420. }
  25421. this._delayedOnLoad = null;
  25422. this._delayedOnError = null;
  25423. };
  25424. // Statics
  25425. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  25426. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  25427. if (onLoad === void 0) { onLoad = null; }
  25428. if (onError === void 0) { onError = null; }
  25429. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  25430. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  25431. };
  25432. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  25433. if (parsedTexture.customType) {
  25434. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  25435. // Update Sampling Mode
  25436. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  25437. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  25438. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  25439. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  25440. }
  25441. }
  25442. return parsedCustomTexture;
  25443. }
  25444. if (parsedTexture.isCube) {
  25445. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  25446. }
  25447. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  25448. return null;
  25449. }
  25450. var texture = BABYLON.SerializationHelper.Parse(function () {
  25451. var generateMipMaps = true;
  25452. if (parsedTexture.noMipmap) {
  25453. generateMipMaps = false;
  25454. }
  25455. if (parsedTexture.mirrorPlane) {
  25456. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  25457. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  25458. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  25459. return mirrorTexture;
  25460. }
  25461. else if (parsedTexture.isRenderTarget) {
  25462. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  25463. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  25464. return renderTargetTexture;
  25465. }
  25466. else {
  25467. var texture;
  25468. if (parsedTexture.base64String) {
  25469. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  25470. }
  25471. else {
  25472. texture = new Texture(rootUrl + parsedTexture.name, scene, !generateMipMaps);
  25473. }
  25474. return texture;
  25475. }
  25476. }, parsedTexture, scene);
  25477. // Update Sampling Mode
  25478. if (parsedTexture.samplingMode) {
  25479. var sampling = parsedTexture.samplingMode;
  25480. if (texture._samplingMode !== sampling) {
  25481. texture.updateSamplingMode(sampling);
  25482. }
  25483. }
  25484. // Animations
  25485. if (parsedTexture.animations) {
  25486. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  25487. var parsedAnimation = parsedTexture.animations[animationIndex];
  25488. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  25489. }
  25490. }
  25491. return texture;
  25492. };
  25493. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  25494. if (deleteBuffer === void 0) { deleteBuffer = false; }
  25495. if (noMipmap === void 0) { noMipmap = false; }
  25496. if (invertY === void 0) { invertY = true; }
  25497. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  25498. if (onLoad === void 0) { onLoad = null; }
  25499. if (onError === void 0) { onError = null; }
  25500. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  25501. if (name.substr(0, 5) !== "data:") {
  25502. name = "data:" + name;
  25503. }
  25504. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  25505. };
  25506. // Constants
  25507. Texture.NEAREST_SAMPLINGMODE = 1;
  25508. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  25509. Texture.BILINEAR_SAMPLINGMODE = 2;
  25510. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  25511. Texture.TRILINEAR_SAMPLINGMODE = 3;
  25512. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  25513. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  25514. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  25515. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  25516. Texture.NEAREST_LINEAR = 7;
  25517. Texture.NEAREST_NEAREST = 8;
  25518. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  25519. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  25520. Texture.LINEAR_LINEAR = 11;
  25521. Texture.LINEAR_NEAREST = 12;
  25522. Texture.EXPLICIT_MODE = 0;
  25523. Texture.SPHERICAL_MODE = 1;
  25524. Texture.PLANAR_MODE = 2;
  25525. Texture.CUBIC_MODE = 3;
  25526. Texture.PROJECTION_MODE = 4;
  25527. Texture.SKYBOX_MODE = 5;
  25528. Texture.INVCUBIC_MODE = 6;
  25529. Texture.EQUIRECTANGULAR_MODE = 7;
  25530. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  25531. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  25532. Texture.CLAMP_ADDRESSMODE = 0;
  25533. Texture.WRAP_ADDRESSMODE = 1;
  25534. Texture.MIRROR_ADDRESSMODE = 2;
  25535. __decorate([
  25536. BABYLON.serialize()
  25537. ], Texture.prototype, "url", void 0);
  25538. __decorate([
  25539. BABYLON.serialize()
  25540. ], Texture.prototype, "uOffset", void 0);
  25541. __decorate([
  25542. BABYLON.serialize()
  25543. ], Texture.prototype, "vOffset", void 0);
  25544. __decorate([
  25545. BABYLON.serialize()
  25546. ], Texture.prototype, "uScale", void 0);
  25547. __decorate([
  25548. BABYLON.serialize()
  25549. ], Texture.prototype, "vScale", void 0);
  25550. __decorate([
  25551. BABYLON.serialize()
  25552. ], Texture.prototype, "uAng", void 0);
  25553. __decorate([
  25554. BABYLON.serialize()
  25555. ], Texture.prototype, "vAng", void 0);
  25556. __decorate([
  25557. BABYLON.serialize()
  25558. ], Texture.prototype, "wAng", void 0);
  25559. __decorate([
  25560. BABYLON.serialize()
  25561. ], Texture.prototype, "isBlocking", null);
  25562. return Texture;
  25563. }(BABYLON.BaseTexture));
  25564. BABYLON.Texture = Texture;
  25565. })(BABYLON || (BABYLON = {}));
  25566. //# sourceMappingURL=babylon.texture.js.map
  25567. var BABYLON;
  25568. (function (BABYLON) {
  25569. var _InstancesBatch = /** @class */ (function () {
  25570. function _InstancesBatch() {
  25571. this.mustReturn = false;
  25572. this.visibleInstances = new Array();
  25573. this.renderSelf = new Array();
  25574. }
  25575. return _InstancesBatch;
  25576. }());
  25577. BABYLON._InstancesBatch = _InstancesBatch;
  25578. var Mesh = /** @class */ (function (_super) {
  25579. __extends(Mesh, _super);
  25580. /**
  25581. * @constructor
  25582. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  25583. * @param {Scene} scene The scene to add this mesh to.
  25584. * @param {Node} parent The parent of this mesh, if it has one
  25585. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  25586. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  25587. * When false, achieved by calling a clone(), also passing False.
  25588. * This will make creation of children, recursive.
  25589. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  25590. */
  25591. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  25592. if (scene === void 0) { scene = null; }
  25593. if (parent === void 0) { parent = null; }
  25594. if (source === void 0) { source = null; }
  25595. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  25596. var _this = _super.call(this, name, scene) || this;
  25597. // Events
  25598. /**
  25599. * An event triggered before rendering the mesh
  25600. * @type {BABYLON.Observable}
  25601. */
  25602. _this.onBeforeRenderObservable = new BABYLON.Observable();
  25603. /**
  25604. * An event triggered after rendering the mesh
  25605. * @type {BABYLON.Observable}
  25606. */
  25607. _this.onAfterRenderObservable = new BABYLON.Observable();
  25608. /**
  25609. * An event triggered before drawing the mesh
  25610. * @type {BABYLON.Observable}
  25611. */
  25612. _this.onBeforeDrawObservable = new BABYLON.Observable();
  25613. // Members
  25614. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25615. _this.instances = new Array();
  25616. _this._LODLevels = new Array();
  25617. _this._visibleInstances = {};
  25618. _this._renderIdForInstances = new Array();
  25619. _this._batchCache = new _InstancesBatch();
  25620. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  25621. // Use by builder only to know what orientation were the mesh build in.
  25622. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  25623. _this.overrideMaterialSideOrientation = null;
  25624. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  25625. // Will be used to save a source mesh reference, If any
  25626. _this._source = null;
  25627. scene = _this.getScene();
  25628. if (source) {
  25629. // Source mesh
  25630. _this._source = source;
  25631. // Geometry
  25632. if (source._geometry) {
  25633. source._geometry.applyToMesh(_this);
  25634. }
  25635. // Deep copy
  25636. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  25637. // Metadata
  25638. if (source.metadata && source.metadata.clone) {
  25639. _this.metadata = source.metadata.clone();
  25640. }
  25641. else {
  25642. _this.metadata = source.metadata;
  25643. }
  25644. // Tags
  25645. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  25646. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  25647. }
  25648. // Parent
  25649. _this.parent = source.parent;
  25650. // Pivot
  25651. _this.setPivotMatrix(source.getPivotMatrix());
  25652. _this.id = name + "." + source.id;
  25653. // Material
  25654. _this.material = source.material;
  25655. var index;
  25656. if (!doNotCloneChildren) {
  25657. // Children
  25658. var directDescendants = source.getDescendants(true);
  25659. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  25660. var child = directDescendants[index_1];
  25661. if (child.clone) {
  25662. child.clone(name + "." + child.name, _this);
  25663. }
  25664. }
  25665. }
  25666. // Physics clone
  25667. var physicsEngine = _this.getScene().getPhysicsEngine();
  25668. if (clonePhysicsImpostor && physicsEngine) {
  25669. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  25670. if (impostor) {
  25671. _this.physicsImpostor = impostor.clone(_this);
  25672. }
  25673. }
  25674. // Particles
  25675. for (index = 0; index < scene.particleSystems.length; index++) {
  25676. var system = scene.particleSystems[index];
  25677. if (system.emitter === source) {
  25678. system.clone(system.name, _this);
  25679. }
  25680. }
  25681. _this.computeWorldMatrix(true);
  25682. }
  25683. // Parent
  25684. if (parent !== null) {
  25685. _this.parent = parent;
  25686. }
  25687. return _this;
  25688. }
  25689. Object.defineProperty(Mesh, "FRONTSIDE", {
  25690. /**
  25691. * Mesh side orientation : usually the external or front surface
  25692. */
  25693. get: function () {
  25694. return Mesh._FRONTSIDE;
  25695. },
  25696. enumerable: true,
  25697. configurable: true
  25698. });
  25699. Object.defineProperty(Mesh, "BACKSIDE", {
  25700. /**
  25701. * Mesh side orientation : usually the internal or back surface
  25702. */
  25703. get: function () {
  25704. return Mesh._BACKSIDE;
  25705. },
  25706. enumerable: true,
  25707. configurable: true
  25708. });
  25709. Object.defineProperty(Mesh, "DOUBLESIDE", {
  25710. /**
  25711. * Mesh side orientation : both internal and external or front and back surfaces
  25712. */
  25713. get: function () {
  25714. return Mesh._DOUBLESIDE;
  25715. },
  25716. enumerable: true,
  25717. configurable: true
  25718. });
  25719. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  25720. /**
  25721. * Mesh side orientation : by default, `FRONTSIDE`
  25722. */
  25723. get: function () {
  25724. return Mesh._DEFAULTSIDE;
  25725. },
  25726. enumerable: true,
  25727. configurable: true
  25728. });
  25729. Object.defineProperty(Mesh, "NO_CAP", {
  25730. /**
  25731. * Mesh cap setting : no cap
  25732. */
  25733. get: function () {
  25734. return Mesh._NO_CAP;
  25735. },
  25736. enumerable: true,
  25737. configurable: true
  25738. });
  25739. Object.defineProperty(Mesh, "CAP_START", {
  25740. /**
  25741. * Mesh cap setting : one cap at the beginning of the mesh
  25742. */
  25743. get: function () {
  25744. return Mesh._CAP_START;
  25745. },
  25746. enumerable: true,
  25747. configurable: true
  25748. });
  25749. Object.defineProperty(Mesh, "CAP_END", {
  25750. /**
  25751. * Mesh cap setting : one cap at the end of the mesh
  25752. */
  25753. get: function () {
  25754. return Mesh._CAP_END;
  25755. },
  25756. enumerable: true,
  25757. configurable: true
  25758. });
  25759. Object.defineProperty(Mesh, "CAP_ALL", {
  25760. /**
  25761. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  25762. */
  25763. get: function () {
  25764. return Mesh._CAP_ALL;
  25765. },
  25766. enumerable: true,
  25767. configurable: true
  25768. });
  25769. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  25770. set: function (callback) {
  25771. if (this._onBeforeDrawObserver) {
  25772. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  25773. }
  25774. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  25775. },
  25776. enumerable: true,
  25777. configurable: true
  25778. });
  25779. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  25780. get: function () {
  25781. return this._morphTargetManager;
  25782. },
  25783. set: function (value) {
  25784. if (this._morphTargetManager === value) {
  25785. return;
  25786. }
  25787. this._morphTargetManager = value;
  25788. this._syncGeometryWithMorphTargetManager();
  25789. },
  25790. enumerable: true,
  25791. configurable: true
  25792. });
  25793. Object.defineProperty(Mesh.prototype, "source", {
  25794. get: function () {
  25795. return this._source;
  25796. },
  25797. enumerable: true,
  25798. configurable: true
  25799. });
  25800. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  25801. get: function () {
  25802. return this._unIndexed;
  25803. },
  25804. set: function (value) {
  25805. if (this._unIndexed !== value) {
  25806. this._unIndexed = value;
  25807. this._markSubMeshesAsAttributesDirty();
  25808. }
  25809. },
  25810. enumerable: true,
  25811. configurable: true
  25812. });
  25813. // Methods
  25814. /**
  25815. * Returns the string "Mesh".
  25816. */
  25817. Mesh.prototype.getClassName = function () {
  25818. return "Mesh";
  25819. };
  25820. /**
  25821. * Returns a string.
  25822. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  25823. */
  25824. Mesh.prototype.toString = function (fullDetails) {
  25825. var ret = _super.prototype.toString.call(this, fullDetails);
  25826. ret += ", n vertices: " + this.getTotalVertices();
  25827. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  25828. if (this.animations) {
  25829. for (var i = 0; i < this.animations.length; i++) {
  25830. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  25831. }
  25832. }
  25833. if (fullDetails) {
  25834. if (this._geometry) {
  25835. var ib = this.getIndices();
  25836. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25837. if (vb && ib) {
  25838. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  25839. }
  25840. }
  25841. else {
  25842. ret += ", flat shading: UNKNOWN";
  25843. }
  25844. }
  25845. return ret;
  25846. };
  25847. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  25848. /**
  25849. * True if the mesh has some Levels Of Details (LOD).
  25850. * Returns a boolean.
  25851. */
  25852. get: function () {
  25853. return this._LODLevels.length > 0;
  25854. },
  25855. enumerable: true,
  25856. configurable: true
  25857. });
  25858. /**
  25859. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  25860. * @returns an array of {BABYLON.MeshLODLevel}
  25861. */
  25862. Mesh.prototype.getLODLevels = function () {
  25863. return this._LODLevels;
  25864. };
  25865. Mesh.prototype._sortLODLevels = function () {
  25866. this._LODLevels.sort(function (a, b) {
  25867. if (a.distance < b.distance) {
  25868. return 1;
  25869. }
  25870. if (a.distance > b.distance) {
  25871. return -1;
  25872. }
  25873. return 0;
  25874. });
  25875. };
  25876. /**
  25877. * Add a mesh as LOD level triggered at the given distance.
  25878. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  25879. * @param {number} distance The distance from the center of the object to show this level
  25880. * @param {Mesh} mesh The mesh to be added as LOD level
  25881. * @return {Mesh} This mesh (for chaining)
  25882. */
  25883. Mesh.prototype.addLODLevel = function (distance, mesh) {
  25884. if (mesh && mesh._masterMesh) {
  25885. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  25886. return this;
  25887. }
  25888. var level = new BABYLON.MeshLODLevel(distance, mesh);
  25889. this._LODLevels.push(level);
  25890. if (mesh) {
  25891. mesh._masterMesh = this;
  25892. }
  25893. this._sortLODLevels();
  25894. return this;
  25895. };
  25896. /**
  25897. * Returns the LOD level mesh at the passed distance or null if not found.
  25898. * It is related to the method `addLODLevel(distance, mesh)`.
  25899. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  25900. * Returns an object Mesh or `null`.
  25901. */
  25902. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  25903. for (var index = 0; index < this._LODLevels.length; index++) {
  25904. var level = this._LODLevels[index];
  25905. if (level.distance === distance) {
  25906. return level.mesh;
  25907. }
  25908. }
  25909. return null;
  25910. };
  25911. /**
  25912. * Remove a mesh from the LOD array
  25913. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  25914. * @param {Mesh} mesh The mesh to be removed.
  25915. * @return {Mesh} This mesh (for chaining)
  25916. */
  25917. Mesh.prototype.removeLODLevel = function (mesh) {
  25918. for (var index = 0; index < this._LODLevels.length; index++) {
  25919. if (this._LODLevels[index].mesh === mesh) {
  25920. this._LODLevels.splice(index, 1);
  25921. if (mesh) {
  25922. mesh._masterMesh = null;
  25923. }
  25924. }
  25925. }
  25926. this._sortLODLevels();
  25927. return this;
  25928. };
  25929. /**
  25930. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  25931. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  25932. */
  25933. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  25934. if (!this._LODLevels || this._LODLevels.length === 0) {
  25935. return this;
  25936. }
  25937. var bSphere;
  25938. if (boundingSphere) {
  25939. bSphere = boundingSphere;
  25940. }
  25941. else {
  25942. var boundingInfo = this.getBoundingInfo();
  25943. bSphere = boundingInfo.boundingSphere;
  25944. }
  25945. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  25946. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  25947. if (this.onLODLevelSelection) {
  25948. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  25949. }
  25950. return this;
  25951. }
  25952. for (var index = 0; index < this._LODLevels.length; index++) {
  25953. var level = this._LODLevels[index];
  25954. if (level.distance < distanceToCamera) {
  25955. if (level.mesh) {
  25956. level.mesh._preActivate();
  25957. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  25958. }
  25959. if (this.onLODLevelSelection) {
  25960. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  25961. }
  25962. return level.mesh;
  25963. }
  25964. }
  25965. if (this.onLODLevelSelection) {
  25966. this.onLODLevelSelection(distanceToCamera, this, this);
  25967. }
  25968. return this;
  25969. };
  25970. Object.defineProperty(Mesh.prototype, "geometry", {
  25971. /**
  25972. * Returns the mesh internal Geometry object.
  25973. */
  25974. get: function () {
  25975. return this._geometry;
  25976. },
  25977. enumerable: true,
  25978. configurable: true
  25979. });
  25980. /**
  25981. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  25982. */
  25983. Mesh.prototype.getTotalVertices = function () {
  25984. if (this._geometry === null || this._geometry === undefined) {
  25985. return 0;
  25986. }
  25987. return this._geometry.getTotalVertices();
  25988. };
  25989. /**
  25990. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  25991. * 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.
  25992. * You can force the copy with forceCopy === true
  25993. * Returns null if the mesh has no geometry or no vertex buffer.
  25994. * Possible `kind` values :
  25995. * - BABYLON.VertexBuffer.PositionKind
  25996. * - BABYLON.VertexBuffer.UVKind
  25997. * - BABYLON.VertexBuffer.UV2Kind
  25998. * - BABYLON.VertexBuffer.UV3Kind
  25999. * - BABYLON.VertexBuffer.UV4Kind
  26000. * - BABYLON.VertexBuffer.UV5Kind
  26001. * - BABYLON.VertexBuffer.UV6Kind
  26002. * - BABYLON.VertexBuffer.ColorKind
  26003. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26004. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26005. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26006. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26007. */
  26008. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  26009. if (!this._geometry) {
  26010. return null;
  26011. }
  26012. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  26013. };
  26014. /**
  26015. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  26016. * Returns `null` if the mesh has no geometry.
  26017. * Possible `kind` values :
  26018. * - BABYLON.VertexBuffer.PositionKind
  26019. * - BABYLON.VertexBuffer.UVKind
  26020. * - BABYLON.VertexBuffer.UV2Kind
  26021. * - BABYLON.VertexBuffer.UV3Kind
  26022. * - BABYLON.VertexBuffer.UV4Kind
  26023. * - BABYLON.VertexBuffer.UV5Kind
  26024. * - BABYLON.VertexBuffer.UV6Kind
  26025. * - BABYLON.VertexBuffer.ColorKind
  26026. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26027. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26028. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26029. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26030. */
  26031. Mesh.prototype.getVertexBuffer = function (kind) {
  26032. if (!this._geometry) {
  26033. return null;
  26034. }
  26035. return this._geometry.getVertexBuffer(kind);
  26036. };
  26037. /**
  26038. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  26039. * Possible `kind` values :
  26040. * - BABYLON.VertexBuffer.PositionKind
  26041. * - BABYLON.VertexBuffer.UVKind
  26042. * - BABYLON.VertexBuffer.UV2Kind
  26043. * - BABYLON.VertexBuffer.UV3Kind
  26044. * - BABYLON.VertexBuffer.UV4Kind
  26045. * - BABYLON.VertexBuffer.UV5Kind
  26046. * - BABYLON.VertexBuffer.UV6Kind
  26047. * - BABYLON.VertexBuffer.ColorKind
  26048. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26049. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26050. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26051. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26052. */
  26053. Mesh.prototype.isVerticesDataPresent = function (kind) {
  26054. if (!this._geometry) {
  26055. if (this._delayInfo) {
  26056. return this._delayInfo.indexOf(kind) !== -1;
  26057. }
  26058. return false;
  26059. }
  26060. return this._geometry.isVerticesDataPresent(kind);
  26061. };
  26062. /**
  26063. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  26064. * Possible `kind` values :
  26065. * - BABYLON.VertexBuffer.PositionKind
  26066. * - BABYLON.VertexBuffer.UVKind
  26067. * - BABYLON.VertexBuffer.UV2Kind
  26068. * - BABYLON.VertexBuffer.UV3Kind
  26069. * - BABYLON.VertexBuffer.UV4Kind
  26070. * - BABYLON.VertexBuffer.UV5Kind
  26071. * - BABYLON.VertexBuffer.UV6Kind
  26072. * - BABYLON.VertexBuffer.ColorKind
  26073. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26074. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26075. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26076. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26077. */
  26078. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  26079. if (!this._geometry) {
  26080. if (this._delayInfo) {
  26081. return this._delayInfo.indexOf(kind) !== -1;
  26082. }
  26083. return false;
  26084. }
  26085. return this._geometry.isVertexBufferUpdatable(kind);
  26086. };
  26087. /**
  26088. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  26089. * Possible `kind` values :
  26090. * - BABYLON.VertexBuffer.PositionKind
  26091. * - BABYLON.VertexBuffer.UVKind
  26092. * - BABYLON.VertexBuffer.UV2Kind
  26093. * - BABYLON.VertexBuffer.UV3Kind
  26094. * - BABYLON.VertexBuffer.UV4Kind
  26095. * - BABYLON.VertexBuffer.UV5Kind
  26096. * - BABYLON.VertexBuffer.UV6Kind
  26097. * - BABYLON.VertexBuffer.ColorKind
  26098. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26099. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26100. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26101. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26102. */
  26103. Mesh.prototype.getVerticesDataKinds = function () {
  26104. if (!this._geometry) {
  26105. var result = new Array();
  26106. if (this._delayInfo) {
  26107. this._delayInfo.forEach(function (kind, index, array) {
  26108. result.push(kind);
  26109. });
  26110. }
  26111. return result;
  26112. }
  26113. return this._geometry.getVerticesDataKinds();
  26114. };
  26115. /**
  26116. * Returns a positive integer : the total number of indices in this mesh geometry.
  26117. * Returns zero if the mesh has no geometry.
  26118. */
  26119. Mesh.prototype.getTotalIndices = function () {
  26120. if (!this._geometry) {
  26121. return 0;
  26122. }
  26123. return this._geometry.getTotalIndices();
  26124. };
  26125. /**
  26126. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  26127. * 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.
  26128. * Returns an empty array if the mesh has no geometry.
  26129. */
  26130. Mesh.prototype.getIndices = function (copyWhenShared) {
  26131. if (!this._geometry) {
  26132. return [];
  26133. }
  26134. return this._geometry.getIndices(copyWhenShared);
  26135. };
  26136. Object.defineProperty(Mesh.prototype, "isBlocked", {
  26137. get: function () {
  26138. return this._masterMesh !== null && this._masterMesh !== undefined;
  26139. },
  26140. enumerable: true,
  26141. configurable: true
  26142. });
  26143. /**
  26144. * Determine if the current mesh is ready to be rendered
  26145. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  26146. * @returns true if all associated assets are ready (material, textures, shaders)
  26147. */
  26148. Mesh.prototype.isReady = function (forceInstanceSupport) {
  26149. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  26150. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26151. return false;
  26152. }
  26153. if (!_super.prototype.isReady.call(this)) {
  26154. return false;
  26155. }
  26156. if (!this.subMeshes || this.subMeshes.length === 0) {
  26157. return true;
  26158. }
  26159. var engine = this.getEngine();
  26160. var scene = this.getScene();
  26161. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  26162. this.computeWorldMatrix();
  26163. var mat = this.material || scene.defaultMaterial;
  26164. if (mat) {
  26165. if (mat.storeEffectOnSubMeshes) {
  26166. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  26167. var subMesh = _a[_i];
  26168. var effectiveMaterial = subMesh.getMaterial();
  26169. if (effectiveMaterial) {
  26170. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  26171. return false;
  26172. }
  26173. }
  26174. }
  26175. }
  26176. else {
  26177. if (!mat.isReady(this, hardwareInstancedRendering)) {
  26178. return false;
  26179. }
  26180. }
  26181. }
  26182. // Shadows
  26183. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  26184. var light = _c[_b];
  26185. var generator = light.getShadowGenerator();
  26186. if (generator) {
  26187. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  26188. var subMesh = _e[_d];
  26189. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  26190. return false;
  26191. }
  26192. }
  26193. }
  26194. }
  26195. // LOD
  26196. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  26197. var lod = _g[_f];
  26198. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  26199. return false;
  26200. }
  26201. }
  26202. return true;
  26203. };
  26204. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  26205. /**
  26206. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  26207. * This property is pertinent only for updatable parametric shapes.
  26208. */
  26209. get: function () {
  26210. return this._areNormalsFrozen;
  26211. },
  26212. enumerable: true,
  26213. configurable: true
  26214. });
  26215. /**
  26216. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  26217. * It has no effect at all on other shapes.
  26218. * It prevents the mesh normals from being recomputed on next `positions` array update.
  26219. * Returns the Mesh.
  26220. */
  26221. Mesh.prototype.freezeNormals = function () {
  26222. this._areNormalsFrozen = true;
  26223. return this;
  26224. };
  26225. /**
  26226. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  26227. * It has no effect at all on other shapes.
  26228. * It reactivates the mesh normals computation if it was previously frozen.
  26229. * Returns the Mesh.
  26230. */
  26231. Mesh.prototype.unfreezeNormals = function () {
  26232. this._areNormalsFrozen = false;
  26233. return this;
  26234. };
  26235. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  26236. /**
  26237. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  26238. */
  26239. set: function (count) {
  26240. this._overridenInstanceCount = count;
  26241. },
  26242. enumerable: true,
  26243. configurable: true
  26244. });
  26245. // Methods
  26246. Mesh.prototype._preActivate = function () {
  26247. var sceneRenderId = this.getScene().getRenderId();
  26248. if (this._preActivateId === sceneRenderId) {
  26249. return this;
  26250. }
  26251. this._preActivateId = sceneRenderId;
  26252. this._visibleInstances = null;
  26253. return this;
  26254. };
  26255. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  26256. if (this._visibleInstances) {
  26257. this._visibleInstances.intermediateDefaultRenderId = renderId;
  26258. }
  26259. return this;
  26260. };
  26261. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  26262. if (!this._visibleInstances) {
  26263. this._visibleInstances = {};
  26264. this._visibleInstances.defaultRenderId = renderId;
  26265. this._visibleInstances.selfDefaultRenderId = this._renderId;
  26266. }
  26267. if (!this._visibleInstances[renderId]) {
  26268. this._visibleInstances[renderId] = new Array();
  26269. }
  26270. this._visibleInstances[renderId].push(instance);
  26271. return this;
  26272. };
  26273. /**
  26274. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  26275. * This means the mesh underlying bounding box and sphere are recomputed.
  26276. * Returns the Mesh.
  26277. */
  26278. Mesh.prototype.refreshBoundingInfo = function () {
  26279. return this._refreshBoundingInfo(false);
  26280. };
  26281. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  26282. if (this._boundingInfo && this._boundingInfo.isLocked) {
  26283. return this;
  26284. }
  26285. var data = this._getPositionData(applySkeleton);
  26286. if (data) {
  26287. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  26288. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  26289. }
  26290. if (this.subMeshes) {
  26291. for (var index = 0; index < this.subMeshes.length; index++) {
  26292. this.subMeshes[index].refreshBoundingInfo();
  26293. }
  26294. }
  26295. this._updateBoundingInfo();
  26296. return this;
  26297. };
  26298. Mesh.prototype._getPositionData = function (applySkeleton) {
  26299. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26300. if (data && applySkeleton && this.skeleton) {
  26301. data = BABYLON.Tools.Slice(data);
  26302. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  26303. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  26304. if (matricesWeightsData && matricesIndicesData) {
  26305. var needExtras = this.numBoneInfluencers > 4;
  26306. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  26307. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  26308. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  26309. var tempVector = BABYLON.Tmp.Vector3[0];
  26310. var finalMatrix = BABYLON.Tmp.Matrix[0];
  26311. var tempMatrix = BABYLON.Tmp.Matrix[1];
  26312. var matWeightIdx = 0;
  26313. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  26314. finalMatrix.reset();
  26315. var inf;
  26316. var weight;
  26317. for (inf = 0; inf < 4; inf++) {
  26318. weight = matricesWeightsData[matWeightIdx + inf];
  26319. if (weight <= 0)
  26320. break;
  26321. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  26322. finalMatrix.addToSelf(tempMatrix);
  26323. }
  26324. if (needExtras) {
  26325. for (inf = 0; inf < 4; inf++) {
  26326. weight = matricesWeightsExtraData[matWeightIdx + inf];
  26327. if (weight <= 0)
  26328. break;
  26329. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  26330. finalMatrix.addToSelf(tempMatrix);
  26331. }
  26332. }
  26333. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  26334. tempVector.toArray(data, index);
  26335. }
  26336. }
  26337. }
  26338. return data;
  26339. };
  26340. Mesh.prototype._createGlobalSubMesh = function (force) {
  26341. var totalVertices = this.getTotalVertices();
  26342. if (!totalVertices || !this.getIndices()) {
  26343. return null;
  26344. }
  26345. // Check if we need to recreate the submeshes
  26346. if (this.subMeshes && this.subMeshes.length > 0) {
  26347. var ib = this.getIndices();
  26348. if (!ib) {
  26349. return null;
  26350. }
  26351. var totalIndices = ib.length;
  26352. var needToRecreate = false;
  26353. if (force) {
  26354. needToRecreate = true;
  26355. }
  26356. else {
  26357. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  26358. var submesh = _a[_i];
  26359. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  26360. needToRecreate = true;
  26361. break;
  26362. }
  26363. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  26364. needToRecreate = true;
  26365. break;
  26366. }
  26367. }
  26368. }
  26369. if (!needToRecreate) {
  26370. return this.subMeshes[0];
  26371. }
  26372. }
  26373. this.releaseSubMeshes();
  26374. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  26375. };
  26376. Mesh.prototype.subdivide = function (count) {
  26377. if (count < 1) {
  26378. return;
  26379. }
  26380. var totalIndices = this.getTotalIndices();
  26381. var subdivisionSize = (totalIndices / count) | 0;
  26382. var offset = 0;
  26383. // Ensure that subdivisionSize is a multiple of 3
  26384. while (subdivisionSize % 3 !== 0) {
  26385. subdivisionSize++;
  26386. }
  26387. this.releaseSubMeshes();
  26388. for (var index = 0; index < count; index++) {
  26389. if (offset >= totalIndices) {
  26390. break;
  26391. }
  26392. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  26393. offset += subdivisionSize;
  26394. }
  26395. this.synchronizeInstances();
  26396. };
  26397. /**
  26398. * Sets the vertex data of the mesh geometry for the requested `kind`.
  26399. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  26400. * The `data` are either a numeric array either a Float32Array.
  26401. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  26402. * 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).
  26403. * Note that a new underlying VertexBuffer object is created each call.
  26404. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  26405. *
  26406. * Possible `kind` values :
  26407. * - BABYLON.VertexBuffer.PositionKind
  26408. * - BABYLON.VertexBuffer.UVKind
  26409. * - BABYLON.VertexBuffer.UV2Kind
  26410. * - BABYLON.VertexBuffer.UV3Kind
  26411. * - BABYLON.VertexBuffer.UV4Kind
  26412. * - BABYLON.VertexBuffer.UV5Kind
  26413. * - BABYLON.VertexBuffer.UV6Kind
  26414. * - BABYLON.VertexBuffer.ColorKind
  26415. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26416. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26417. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26418. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26419. *
  26420. * Returns the Mesh.
  26421. */
  26422. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  26423. if (updatable === void 0) { updatable = false; }
  26424. if (!this._geometry) {
  26425. var vertexData = new BABYLON.VertexData();
  26426. vertexData.set(data, kind);
  26427. var scene = this.getScene();
  26428. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  26429. }
  26430. else {
  26431. this._geometry.setVerticesData(kind, data, updatable, stride);
  26432. }
  26433. return this;
  26434. };
  26435. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  26436. if (updatable === void 0) { updatable = true; }
  26437. var vb = this.getVertexBuffer(kind);
  26438. if (!vb || vb.isUpdatable() === updatable) {
  26439. return;
  26440. }
  26441. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  26442. };
  26443. /**
  26444. * Sets the mesh VertexBuffer.
  26445. * Returns the Mesh.
  26446. */
  26447. Mesh.prototype.setVerticesBuffer = function (buffer) {
  26448. if (!this._geometry) {
  26449. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  26450. }
  26451. this._geometry.setVerticesBuffer(buffer);
  26452. return this;
  26453. };
  26454. /**
  26455. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  26456. * If the mesh has no geometry, it is simply returned as it is.
  26457. * The `data` are either a numeric array either a Float32Array.
  26458. * No new underlying VertexBuffer object is created.
  26459. * 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.
  26460. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  26461. *
  26462. * Possible `kind` values :
  26463. * - BABYLON.VertexBuffer.PositionKind
  26464. * - BABYLON.VertexBuffer.UVKind
  26465. * - BABYLON.VertexBuffer.UV2Kind
  26466. * - BABYLON.VertexBuffer.UV3Kind
  26467. * - BABYLON.VertexBuffer.UV4Kind
  26468. * - BABYLON.VertexBuffer.UV5Kind
  26469. * - BABYLON.VertexBuffer.UV6Kind
  26470. * - BABYLON.VertexBuffer.ColorKind
  26471. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26472. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26473. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26474. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26475. *
  26476. * Returns the Mesh.
  26477. */
  26478. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  26479. if (!this._geometry) {
  26480. return this;
  26481. }
  26482. if (!makeItUnique) {
  26483. this._geometry.updateVerticesData(kind, data, updateExtends);
  26484. }
  26485. else {
  26486. this.makeGeometryUnique();
  26487. this.updateVerticesData(kind, data, updateExtends, false);
  26488. }
  26489. return this;
  26490. };
  26491. /**
  26492. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  26493. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  26494. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  26495. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  26496. * Returns the Mesh.
  26497. */
  26498. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  26499. if (computeNormals === void 0) { computeNormals = true; }
  26500. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26501. if (!positions) {
  26502. return this;
  26503. }
  26504. positionFunction(positions);
  26505. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  26506. if (computeNormals) {
  26507. var indices = this.getIndices();
  26508. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26509. if (!normals) {
  26510. return this;
  26511. }
  26512. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  26513. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  26514. }
  26515. return this;
  26516. };
  26517. /**
  26518. * Creates a un-shared specific occurence of the geometry for the mesh.
  26519. * Returns the Mesh.
  26520. */
  26521. Mesh.prototype.makeGeometryUnique = function () {
  26522. if (!this._geometry) {
  26523. return this;
  26524. }
  26525. var oldGeometry = this._geometry;
  26526. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  26527. oldGeometry.releaseForMesh(this, true);
  26528. geometry.applyToMesh(this);
  26529. return this;
  26530. };
  26531. /**
  26532. * Sets the mesh indices.
  26533. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  26534. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  26535. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  26536. * This method creates a new index buffer each call.
  26537. * Returns the Mesh.
  26538. */
  26539. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  26540. if (totalVertices === void 0) { totalVertices = null; }
  26541. if (updatable === void 0) { updatable = false; }
  26542. if (!this._geometry) {
  26543. var vertexData = new BABYLON.VertexData();
  26544. vertexData.indices = indices;
  26545. var scene = this.getScene();
  26546. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  26547. }
  26548. else {
  26549. this._geometry.setIndices(indices, totalVertices, updatable);
  26550. }
  26551. return this;
  26552. };
  26553. /**
  26554. * Update the current index buffer
  26555. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  26556. * Returns the Mesh.
  26557. */
  26558. Mesh.prototype.updateIndices = function (indices, offset) {
  26559. if (!this._geometry) {
  26560. return this;
  26561. }
  26562. this._geometry.updateIndices(indices, offset);
  26563. return this;
  26564. };
  26565. /**
  26566. * Invert the geometry to move from a right handed system to a left handed one.
  26567. * Returns the Mesh.
  26568. */
  26569. Mesh.prototype.toLeftHanded = function () {
  26570. if (!this._geometry) {
  26571. return this;
  26572. }
  26573. this._geometry.toLeftHanded();
  26574. return this;
  26575. };
  26576. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  26577. if (!this._geometry) {
  26578. return this;
  26579. }
  26580. var engine = this.getScene().getEngine();
  26581. // Wireframe
  26582. var indexToBind;
  26583. if (this._unIndexed) {
  26584. indexToBind = null;
  26585. }
  26586. else {
  26587. switch (fillMode) {
  26588. case BABYLON.Material.PointFillMode:
  26589. indexToBind = null;
  26590. break;
  26591. case BABYLON.Material.WireFrameFillMode:
  26592. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  26593. break;
  26594. default:
  26595. case BABYLON.Material.TriangleFillMode:
  26596. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  26597. break;
  26598. }
  26599. }
  26600. // VBOs
  26601. this._geometry._bind(effect, indexToBind);
  26602. return this;
  26603. };
  26604. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  26605. if (alternate === void 0) { alternate = false; }
  26606. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  26607. return this;
  26608. }
  26609. this.onBeforeDrawObservable.notifyObservers(this);
  26610. var scene = this.getScene();
  26611. var engine = scene.getEngine();
  26612. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  26613. // or triangles as points
  26614. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  26615. }
  26616. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  26617. // Triangles as wireframe
  26618. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  26619. }
  26620. else {
  26621. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  26622. }
  26623. if (scene._isAlternateRenderingEnabled && !alternate) {
  26624. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  26625. if (!effect || !scene.activeCamera) {
  26626. return this;
  26627. }
  26628. scene._switchToAlternateCameraConfiguration(true);
  26629. this._effectiveMaterial.bindView(effect);
  26630. this._effectiveMaterial.bindViewProjection(effect);
  26631. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  26632. this._draw(subMesh, fillMode, instancesCount, true);
  26633. engine.setViewport(scene.activeCamera.viewport);
  26634. scene._switchToAlternateCameraConfiguration(false);
  26635. this._effectiveMaterial.bindView(effect);
  26636. this._effectiveMaterial.bindViewProjection(effect);
  26637. }
  26638. return this;
  26639. };
  26640. /**
  26641. * Registers for this mesh a javascript function called just before the rendering process.
  26642. * This function is passed the current mesh.
  26643. * Return the Mesh.
  26644. */
  26645. Mesh.prototype.registerBeforeRender = function (func) {
  26646. this.onBeforeRenderObservable.add(func);
  26647. return this;
  26648. };
  26649. /**
  26650. * Disposes a previously registered javascript function called before the rendering.
  26651. * This function is passed the current mesh.
  26652. * Returns the Mesh.
  26653. */
  26654. Mesh.prototype.unregisterBeforeRender = function (func) {
  26655. this.onBeforeRenderObservable.removeCallback(func);
  26656. return this;
  26657. };
  26658. /**
  26659. * Registers for this mesh a javascript function called just after the rendering is complete.
  26660. * This function is passed the current mesh.
  26661. * Returns the Mesh.
  26662. */
  26663. Mesh.prototype.registerAfterRender = function (func) {
  26664. this.onAfterRenderObservable.add(func);
  26665. return this;
  26666. };
  26667. /**
  26668. * Disposes a previously registered javascript function called after the rendering.
  26669. * This function is passed the current mesh.
  26670. * Return the Mesh.
  26671. */
  26672. Mesh.prototype.unregisterAfterRender = function (func) {
  26673. this.onAfterRenderObservable.removeCallback(func);
  26674. return this;
  26675. };
  26676. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  26677. var scene = this.getScene();
  26678. this._batchCache.mustReturn = false;
  26679. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  26680. this._batchCache.visibleInstances[subMeshId] = null;
  26681. if (this._visibleInstances) {
  26682. var currentRenderId = scene.getRenderId();
  26683. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  26684. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  26685. var selfRenderId = this._renderId;
  26686. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  26687. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  26688. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  26689. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  26690. }
  26691. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  26692. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  26693. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  26694. this._batchCache.mustReturn = true;
  26695. return this._batchCache;
  26696. }
  26697. if (currentRenderId !== selfRenderId) {
  26698. this._batchCache.renderSelf[subMeshId] = false;
  26699. }
  26700. }
  26701. this._renderIdForInstances[subMeshId] = currentRenderId;
  26702. }
  26703. return this._batchCache;
  26704. };
  26705. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  26706. var visibleInstances = batch.visibleInstances[subMesh._id];
  26707. if (!visibleInstances) {
  26708. return this;
  26709. }
  26710. var matricesCount = visibleInstances.length + 1;
  26711. var bufferSize = matricesCount * 16 * 4;
  26712. var currentInstancesBufferSize = this._instancesBufferSize;
  26713. var instancesBuffer = this._instancesBuffer;
  26714. while (this._instancesBufferSize < bufferSize) {
  26715. this._instancesBufferSize *= 2;
  26716. }
  26717. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  26718. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  26719. }
  26720. var offset = 0;
  26721. var instancesCount = 0;
  26722. var world = this.getWorldMatrix();
  26723. if (batch.renderSelf[subMesh._id]) {
  26724. world.copyToArray(this._instancesData, offset);
  26725. offset += 16;
  26726. instancesCount++;
  26727. }
  26728. if (visibleInstances) {
  26729. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  26730. var instance = visibleInstances[instanceIndex];
  26731. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  26732. offset += 16;
  26733. instancesCount++;
  26734. }
  26735. }
  26736. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  26737. if (instancesBuffer) {
  26738. instancesBuffer.dispose();
  26739. }
  26740. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  26741. this._instancesBuffer = instancesBuffer;
  26742. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  26743. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  26744. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  26745. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  26746. }
  26747. else {
  26748. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  26749. }
  26750. this._bind(subMesh, effect, fillMode);
  26751. this._draw(subMesh, fillMode, instancesCount);
  26752. engine.unbindInstanceAttributes();
  26753. return this;
  26754. };
  26755. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  26756. var scene = this.getScene();
  26757. var engine = scene.getEngine();
  26758. if (hardwareInstancedRendering) {
  26759. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  26760. }
  26761. else {
  26762. if (batch.renderSelf[subMesh._id]) {
  26763. // Draw
  26764. if (onBeforeDraw) {
  26765. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  26766. }
  26767. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  26768. }
  26769. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  26770. if (visibleInstancesForSubMesh) {
  26771. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  26772. var instance = visibleInstancesForSubMesh[instanceIndex];
  26773. // World
  26774. var world = instance.getWorldMatrix();
  26775. if (onBeforeDraw) {
  26776. onBeforeDraw(true, world, effectiveMaterial);
  26777. }
  26778. // Draw
  26779. this._draw(subMesh, fillMode);
  26780. }
  26781. }
  26782. }
  26783. return this;
  26784. };
  26785. /**
  26786. * Triggers the draw call for the mesh.
  26787. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  26788. * Returns the Mesh.
  26789. */
  26790. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  26791. this.checkOcclusionQuery();
  26792. if (this._isOccluded) {
  26793. return this;
  26794. }
  26795. var scene = this.getScene();
  26796. // Managing instances
  26797. var batch = this._getInstancesRenderList(subMesh._id);
  26798. if (batch.mustReturn) {
  26799. return this;
  26800. }
  26801. // Checking geometry state
  26802. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  26803. return this;
  26804. }
  26805. this.onBeforeRenderObservable.notifyObservers(this);
  26806. var engine = scene.getEngine();
  26807. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  26808. // Material
  26809. var material = subMesh.getMaterial();
  26810. if (!material) {
  26811. return this;
  26812. }
  26813. this._effectiveMaterial = material;
  26814. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  26815. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  26816. return this;
  26817. }
  26818. }
  26819. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  26820. return this;
  26821. }
  26822. // Alpha mode
  26823. if (enableAlphaMode) {
  26824. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  26825. }
  26826. // Outline - step 1
  26827. var savedDepthWrite = engine.getDepthWrite();
  26828. if (this.renderOutline) {
  26829. engine.setDepthWrite(false);
  26830. scene.getOutlineRenderer().render(subMesh, batch);
  26831. engine.setDepthWrite(savedDepthWrite);
  26832. }
  26833. var effect;
  26834. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  26835. effect = subMesh.effect;
  26836. }
  26837. else {
  26838. effect = this._effectiveMaterial.getEffect();
  26839. }
  26840. if (!effect) {
  26841. return this;
  26842. }
  26843. var sideOrientation = this.overrideMaterialSideOrientation;
  26844. if (sideOrientation == null) {
  26845. sideOrientation = this._effectiveMaterial.sideOrientation;
  26846. if (this._getWorldMatrixDeterminant() < 0) {
  26847. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  26848. }
  26849. }
  26850. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  26851. if (this._effectiveMaterial.forceDepthWrite) {
  26852. engine.setDepthWrite(true);
  26853. }
  26854. // Bind
  26855. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  26856. if (!hardwareInstancedRendering) {
  26857. this._bind(subMesh, effect, fillMode);
  26858. }
  26859. var world = this.getWorldMatrix();
  26860. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  26861. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  26862. }
  26863. else {
  26864. this._effectiveMaterial.bind(world, this);
  26865. }
  26866. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  26867. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  26868. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  26869. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  26870. }
  26871. // Draw
  26872. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  26873. // Unbind
  26874. this._effectiveMaterial.unbind();
  26875. // Outline - step 2
  26876. if (this.renderOutline && savedDepthWrite) {
  26877. engine.setDepthWrite(true);
  26878. engine.setColorWrite(false);
  26879. scene.getOutlineRenderer().render(subMesh, batch);
  26880. engine.setColorWrite(true);
  26881. }
  26882. // Overlay
  26883. if (this.renderOverlay) {
  26884. var currentMode = engine.getAlphaMode();
  26885. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  26886. scene.getOutlineRenderer().render(subMesh, batch, true);
  26887. engine.setAlphaMode(currentMode);
  26888. }
  26889. this.onAfterRenderObservable.notifyObservers(this);
  26890. return this;
  26891. };
  26892. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  26893. if (isInstance && effectiveMaterial) {
  26894. effectiveMaterial.bindOnlyWorldMatrix(world);
  26895. }
  26896. };
  26897. /**
  26898. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  26899. */
  26900. Mesh.prototype.getEmittedParticleSystems = function () {
  26901. var results = new Array();
  26902. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  26903. var particleSystem = this.getScene().particleSystems[index];
  26904. if (particleSystem.emitter === this) {
  26905. results.push(particleSystem);
  26906. }
  26907. }
  26908. return results;
  26909. };
  26910. /**
  26911. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  26912. */
  26913. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  26914. var results = new Array();
  26915. var descendants = this.getDescendants();
  26916. descendants.push(this);
  26917. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  26918. var particleSystem = this.getScene().particleSystems[index];
  26919. var emitter = particleSystem.emitter;
  26920. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  26921. results.push(particleSystem);
  26922. }
  26923. }
  26924. return results;
  26925. };
  26926. Mesh.prototype._checkDelayState = function () {
  26927. var scene = this.getScene();
  26928. if (this._geometry) {
  26929. this._geometry.load(scene);
  26930. }
  26931. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26932. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  26933. this._queueLoad(scene);
  26934. }
  26935. return this;
  26936. };
  26937. Mesh.prototype._queueLoad = function (scene) {
  26938. var _this = this;
  26939. scene._addPendingData(this);
  26940. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  26941. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  26942. if (data instanceof ArrayBuffer) {
  26943. _this._delayLoadingFunction(data, _this);
  26944. }
  26945. else {
  26946. _this._delayLoadingFunction(JSON.parse(data), _this);
  26947. }
  26948. _this.instances.forEach(function (instance) {
  26949. instance._syncSubMeshes();
  26950. });
  26951. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26952. scene._removePendingData(_this);
  26953. }, function () { }, scene.database, getBinaryData);
  26954. return this;
  26955. };
  26956. /**
  26957. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  26958. */
  26959. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  26960. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26961. return false;
  26962. }
  26963. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  26964. return false;
  26965. }
  26966. this._checkDelayState();
  26967. return true;
  26968. };
  26969. /**
  26970. * Sets the mesh material by the material or multiMaterial `id` property.
  26971. * The material `id` is a string identifying the material or the multiMaterial.
  26972. * This method returns the Mesh.
  26973. */
  26974. Mesh.prototype.setMaterialByID = function (id) {
  26975. var materials = this.getScene().materials;
  26976. var index;
  26977. for (index = materials.length - 1; index > -1; index--) {
  26978. if (materials[index].id === id) {
  26979. this.material = materials[index];
  26980. return this;
  26981. }
  26982. }
  26983. // Multi
  26984. var multiMaterials = this.getScene().multiMaterials;
  26985. for (index = multiMaterials.length - 1; index > -1; index--) {
  26986. if (multiMaterials[index].id === id) {
  26987. this.material = multiMaterials[index];
  26988. return this;
  26989. }
  26990. }
  26991. return this;
  26992. };
  26993. /**
  26994. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  26995. */
  26996. Mesh.prototype.getAnimatables = function () {
  26997. var results = new Array();
  26998. if (this.material) {
  26999. results.push(this.material);
  27000. }
  27001. if (this.skeleton) {
  27002. results.push(this.skeleton);
  27003. }
  27004. return results;
  27005. };
  27006. /**
  27007. * Modifies the mesh geometry according to the passed transformation matrix.
  27008. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  27009. * The mesh normals are modified accordingly the same transformation.
  27010. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  27011. * Note that, under the hood, this method sets a new VertexBuffer each call.
  27012. * Returns the Mesh.
  27013. */
  27014. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  27015. // Position
  27016. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27017. return this;
  27018. }
  27019. var submeshes = this.subMeshes.splice(0);
  27020. this._resetPointsArrayCache();
  27021. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27022. var temp = new Array();
  27023. var index;
  27024. for (index = 0; index < data.length; index += 3) {
  27025. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  27026. }
  27027. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  27028. // Normals
  27029. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27030. return this;
  27031. }
  27032. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27033. temp = [];
  27034. for (index = 0; index < data.length; index += 3) {
  27035. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  27036. }
  27037. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  27038. // flip faces?
  27039. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  27040. this.flipFaces();
  27041. }
  27042. // Restore submeshes
  27043. this.releaseSubMeshes();
  27044. this.subMeshes = submeshes;
  27045. return this;
  27046. };
  27047. /**
  27048. * Modifies the mesh geometry according to its own current World Matrix.
  27049. * The mesh World Matrix is then reset.
  27050. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  27051. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  27052. * Note that, under the hood, this method sets a new VertexBuffer each call.
  27053. * Returns the Mesh.
  27054. */
  27055. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  27056. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  27057. this.scaling.copyFromFloats(1, 1, 1);
  27058. this.position.copyFromFloats(0, 0, 0);
  27059. this.rotation.copyFromFloats(0, 0, 0);
  27060. //only if quaternion is already set
  27061. if (this.rotationQuaternion) {
  27062. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  27063. }
  27064. this._worldMatrix = BABYLON.Matrix.Identity();
  27065. return this;
  27066. };
  27067. Object.defineProperty(Mesh.prototype, "_positions", {
  27068. // Cache
  27069. get: function () {
  27070. if (this._geometry) {
  27071. return this._geometry._positions;
  27072. }
  27073. return null;
  27074. },
  27075. enumerable: true,
  27076. configurable: true
  27077. });
  27078. Mesh.prototype._resetPointsArrayCache = function () {
  27079. if (this._geometry) {
  27080. this._geometry._resetPointsArrayCache();
  27081. }
  27082. return this;
  27083. };
  27084. Mesh.prototype._generatePointsArray = function () {
  27085. if (this._geometry) {
  27086. return this._geometry._generatePointsArray();
  27087. }
  27088. return false;
  27089. };
  27090. /**
  27091. * Returns a new Mesh object generated from the current mesh properties.
  27092. * This method must not get confused with createInstance().
  27093. * The parameter `name` is a string, the name given to the new mesh.
  27094. * The optional parameter `newParent` can be any Node object (default `null`).
  27095. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  27096. * 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.
  27097. */
  27098. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  27099. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  27100. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  27101. };
  27102. /**
  27103. * Disposes the Mesh.
  27104. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  27105. * Returns nothing.
  27106. */
  27107. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  27108. var _this = this;
  27109. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  27110. this.morphTargetManager = null;
  27111. if (this._geometry) {
  27112. this._geometry.releaseForMesh(this, true);
  27113. }
  27114. // Sources
  27115. var meshes = this.getScene().meshes;
  27116. meshes.forEach(function (abstractMesh) {
  27117. var mesh = abstractMesh;
  27118. if (mesh._source && mesh._source === _this) {
  27119. mesh._source = null;
  27120. }
  27121. });
  27122. this._source = null;
  27123. // Instances
  27124. if (this._instancesBuffer) {
  27125. this._instancesBuffer.dispose();
  27126. this._instancesBuffer = null;
  27127. }
  27128. while (this.instances.length) {
  27129. this.instances[0].dispose();
  27130. }
  27131. // Highlight layers.
  27132. var highlightLayers = this.getScene().highlightLayers;
  27133. for (var i = 0; i < highlightLayers.length; i++) {
  27134. var highlightLayer = highlightLayers[i];
  27135. if (highlightLayer) {
  27136. highlightLayer.removeMesh(this);
  27137. highlightLayer.removeExcludedMesh(this);
  27138. }
  27139. }
  27140. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  27141. };
  27142. /**
  27143. * Modifies the mesh geometry according to a displacement map.
  27144. * 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.
  27145. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  27146. * This method returns nothing.
  27147. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  27148. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  27149. * 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.
  27150. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  27151. * The parameter `uvScale` is an optional vector2 used to scale UV.
  27152. *
  27153. * Returns the Mesh.
  27154. */
  27155. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  27156. var _this = this;
  27157. var scene = this.getScene();
  27158. var onload = function (img) {
  27159. // Getting height map data
  27160. var canvas = document.createElement("canvas");
  27161. var context = canvas.getContext("2d");
  27162. var heightMapWidth = img.width;
  27163. var heightMapHeight = img.height;
  27164. canvas.width = heightMapWidth;
  27165. canvas.height = heightMapHeight;
  27166. context.drawImage(img, 0, 0);
  27167. // Create VertexData from map data
  27168. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  27169. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  27170. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  27171. //execute success callback, if set
  27172. if (onSuccess) {
  27173. onSuccess(_this);
  27174. }
  27175. };
  27176. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  27177. return this;
  27178. };
  27179. /**
  27180. * Modifies the mesh geometry according to a displacementMap buffer.
  27181. * 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.
  27182. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  27183. * This method returns nothing.
  27184. * 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.
  27185. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  27186. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  27187. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  27188. * The parameter `uvScale` is an optional vector2 used to scale UV.
  27189. *
  27190. * Returns the Mesh.
  27191. */
  27192. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  27193. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  27194. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  27195. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27196. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  27197. return this;
  27198. }
  27199. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27200. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27201. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  27202. var position = BABYLON.Vector3.Zero();
  27203. var normal = BABYLON.Vector3.Zero();
  27204. var uv = BABYLON.Vector2.Zero();
  27205. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  27206. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  27207. for (var index = 0; index < positions.length; index += 3) {
  27208. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  27209. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  27210. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  27211. // Compute height
  27212. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  27213. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  27214. var pos = (u + v * heightMapWidth) * 4;
  27215. var r = buffer[pos] / 255.0;
  27216. var g = buffer[pos + 1] / 255.0;
  27217. var b = buffer[pos + 2] / 255.0;
  27218. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  27219. normal.normalize();
  27220. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  27221. position = position.add(normal);
  27222. position.toArray(positions, index);
  27223. }
  27224. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  27225. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  27226. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  27227. return this;
  27228. };
  27229. /**
  27230. * Modify the mesh to get a flat shading rendering.
  27231. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  27232. * This method returns the Mesh.
  27233. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  27234. */
  27235. Mesh.prototype.convertToFlatShadedMesh = function () {
  27236. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  27237. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  27238. var kinds = this.getVerticesDataKinds();
  27239. var vbs = {};
  27240. var data = {};
  27241. var newdata = {};
  27242. var updatableNormals = false;
  27243. var kindIndex;
  27244. var kind;
  27245. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27246. kind = kinds[kindIndex];
  27247. var vertexBuffer = this.getVertexBuffer(kind);
  27248. if (kind === BABYLON.VertexBuffer.NormalKind) {
  27249. updatableNormals = vertexBuffer.isUpdatable();
  27250. kinds.splice(kindIndex, 1);
  27251. kindIndex--;
  27252. continue;
  27253. }
  27254. vbs[kind] = vertexBuffer;
  27255. data[kind] = vbs[kind].getData();
  27256. newdata[kind] = [];
  27257. }
  27258. // Save previous submeshes
  27259. var previousSubmeshes = this.subMeshes.slice(0);
  27260. var indices = this.getIndices();
  27261. var totalIndices = this.getTotalIndices();
  27262. // Generating unique vertices per face
  27263. var index;
  27264. for (index = 0; index < totalIndices; index++) {
  27265. var vertexIndex = indices[index];
  27266. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27267. kind = kinds[kindIndex];
  27268. var stride = vbs[kind].getStrideSize();
  27269. for (var offset = 0; offset < stride; offset++) {
  27270. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  27271. }
  27272. }
  27273. }
  27274. // Updating faces & normal
  27275. var normals = [];
  27276. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  27277. for (index = 0; index < totalIndices; index += 3) {
  27278. indices[index] = index;
  27279. indices[index + 1] = index + 1;
  27280. indices[index + 2] = index + 2;
  27281. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  27282. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  27283. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  27284. var p1p2 = p1.subtract(p2);
  27285. var p3p2 = p3.subtract(p2);
  27286. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  27287. // Store same normals for every vertex
  27288. for (var localIndex = 0; localIndex < 3; localIndex++) {
  27289. normals.push(normal.x);
  27290. normals.push(normal.y);
  27291. normals.push(normal.z);
  27292. }
  27293. }
  27294. this.setIndices(indices);
  27295. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  27296. // Updating vertex buffers
  27297. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27298. kind = kinds[kindIndex];
  27299. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  27300. }
  27301. // Updating submeshes
  27302. this.releaseSubMeshes();
  27303. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  27304. var previousOne = previousSubmeshes[submeshIndex];
  27305. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  27306. }
  27307. this.synchronizeInstances();
  27308. return this;
  27309. };
  27310. /**
  27311. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  27312. * In other words, more vertices, no more indices and a single bigger VBO.
  27313. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  27314. * Returns the Mesh.
  27315. */
  27316. Mesh.prototype.convertToUnIndexedMesh = function () {
  27317. /// <summary>Remove indices by unfolding faces into buffers</summary>
  27318. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  27319. var kinds = this.getVerticesDataKinds();
  27320. var vbs = {};
  27321. var data = {};
  27322. var newdata = {};
  27323. var kindIndex;
  27324. var kind;
  27325. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27326. kind = kinds[kindIndex];
  27327. var vertexBuffer = this.getVertexBuffer(kind);
  27328. vbs[kind] = vertexBuffer;
  27329. data[kind] = vbs[kind].getData();
  27330. newdata[kind] = [];
  27331. }
  27332. // Save previous submeshes
  27333. var previousSubmeshes = this.subMeshes.slice(0);
  27334. var indices = this.getIndices();
  27335. var totalIndices = this.getTotalIndices();
  27336. // Generating unique vertices per face
  27337. var index;
  27338. for (index = 0; index < totalIndices; index++) {
  27339. var vertexIndex = indices[index];
  27340. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27341. kind = kinds[kindIndex];
  27342. var stride = vbs[kind].getStrideSize();
  27343. for (var offset = 0; offset < stride; offset++) {
  27344. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  27345. }
  27346. }
  27347. }
  27348. // Updating indices
  27349. for (index = 0; index < totalIndices; index += 3) {
  27350. indices[index] = index;
  27351. indices[index + 1] = index + 1;
  27352. indices[index + 2] = index + 2;
  27353. }
  27354. this.setIndices(indices);
  27355. // Updating vertex buffers
  27356. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27357. kind = kinds[kindIndex];
  27358. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  27359. }
  27360. // Updating submeshes
  27361. this.releaseSubMeshes();
  27362. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  27363. var previousOne = previousSubmeshes[submeshIndex];
  27364. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  27365. }
  27366. this._unIndexed = true;
  27367. this.synchronizeInstances();
  27368. return this;
  27369. };
  27370. /**
  27371. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  27372. * This method returns the Mesh.
  27373. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  27374. */
  27375. Mesh.prototype.flipFaces = function (flipNormals) {
  27376. if (flipNormals === void 0) { flipNormals = false; }
  27377. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  27378. var i;
  27379. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  27380. for (i = 0; i < vertex_data.normals.length; i++) {
  27381. vertex_data.normals[i] *= -1;
  27382. }
  27383. }
  27384. if (vertex_data.indices) {
  27385. var temp;
  27386. for (i = 0; i < vertex_data.indices.length; i += 3) {
  27387. // reassign indices
  27388. temp = vertex_data.indices[i + 1];
  27389. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  27390. vertex_data.indices[i + 2] = temp;
  27391. }
  27392. }
  27393. vertex_data.applyToMesh(this);
  27394. return this;
  27395. };
  27396. // Instances
  27397. /**
  27398. * Creates a new InstancedMesh object from the mesh model.
  27399. * An instance shares the same properties and the same material than its model.
  27400. * Only these properties of each instance can then be set individually :
  27401. * - position
  27402. * - rotation
  27403. * - rotationQuaternion
  27404. * - setPivotMatrix
  27405. * - scaling
  27406. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  27407. * Warning : this method is not supported for Line mesh and LineSystem
  27408. */
  27409. Mesh.prototype.createInstance = function (name) {
  27410. return new BABYLON.InstancedMesh(name, this);
  27411. };
  27412. /**
  27413. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  27414. * After this call, all the mesh instances have the same submeshes than the current mesh.
  27415. * This method returns the Mesh.
  27416. */
  27417. Mesh.prototype.synchronizeInstances = function () {
  27418. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  27419. var instance = this.instances[instanceIndex];
  27420. instance._syncSubMeshes();
  27421. }
  27422. return this;
  27423. };
  27424. /**
  27425. * Simplify the mesh according to the given array of settings.
  27426. * Function will return immediately and will simplify async. It returns the Mesh.
  27427. * @param settings a collection of simplification settings.
  27428. * @param parallelProcessing should all levels calculate parallel or one after the other.
  27429. * @param type the type of simplification to run.
  27430. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  27431. */
  27432. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  27433. if (parallelProcessing === void 0) { parallelProcessing = true; }
  27434. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  27435. this.getScene().simplificationQueue.addTask({
  27436. settings: settings,
  27437. parallelProcessing: parallelProcessing,
  27438. mesh: this,
  27439. simplificationType: simplificationType,
  27440. successCallback: successCallback
  27441. });
  27442. return this;
  27443. };
  27444. /**
  27445. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  27446. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  27447. * This should be used together with the simplification to avoid disappearing triangles.
  27448. * Returns the Mesh.
  27449. * @param successCallback an optional success callback to be called after the optimization finished.
  27450. */
  27451. Mesh.prototype.optimizeIndices = function (successCallback) {
  27452. var _this = this;
  27453. var indices = this.getIndices();
  27454. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27455. if (!positions || !indices) {
  27456. return this;
  27457. }
  27458. var vectorPositions = new Array();
  27459. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  27460. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  27461. }
  27462. var dupes = new Array();
  27463. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  27464. var realPos = vectorPositions.length - 1 - iteration;
  27465. var testedPosition = vectorPositions[realPos];
  27466. for (var j = 0; j < realPos; ++j) {
  27467. var againstPosition = vectorPositions[j];
  27468. if (testedPosition.equals(againstPosition)) {
  27469. dupes[realPos] = j;
  27470. break;
  27471. }
  27472. }
  27473. }, function () {
  27474. for (var i = 0; i < indices.length; ++i) {
  27475. indices[i] = dupes[indices[i]] || indices[i];
  27476. }
  27477. //indices are now reordered
  27478. var originalSubMeshes = _this.subMeshes.slice(0);
  27479. _this.setIndices(indices);
  27480. _this.subMeshes = originalSubMeshes;
  27481. if (successCallback) {
  27482. successCallback(_this);
  27483. }
  27484. });
  27485. return this;
  27486. };
  27487. Mesh.prototype.serialize = function (serializationObject) {
  27488. serializationObject.name = this.name;
  27489. serializationObject.id = this.id;
  27490. serializationObject.type = this.getClassName();
  27491. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  27492. serializationObject.tags = BABYLON.Tags.GetTags(this);
  27493. }
  27494. serializationObject.position = this.position.asArray();
  27495. if (this.rotationQuaternion) {
  27496. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  27497. }
  27498. else if (this.rotation) {
  27499. serializationObject.rotation = this.rotation.asArray();
  27500. }
  27501. serializationObject.scaling = this.scaling.asArray();
  27502. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  27503. serializationObject.isEnabled = this.isEnabled(false);
  27504. serializationObject.isVisible = this.isVisible;
  27505. serializationObject.infiniteDistance = this.infiniteDistance;
  27506. serializationObject.pickable = this.isPickable;
  27507. serializationObject.receiveShadows = this.receiveShadows;
  27508. serializationObject.billboardMode = this.billboardMode;
  27509. serializationObject.visibility = this.visibility;
  27510. serializationObject.checkCollisions = this.checkCollisions;
  27511. serializationObject.isBlocker = this.isBlocker;
  27512. // Parent
  27513. if (this.parent) {
  27514. serializationObject.parentId = this.parent.id;
  27515. }
  27516. // Geometry
  27517. serializationObject.isUnIndexed = this.isUnIndexed;
  27518. var geometry = this._geometry;
  27519. if (geometry) {
  27520. var geometryId = geometry.id;
  27521. serializationObject.geometryId = geometryId;
  27522. // SubMeshes
  27523. serializationObject.subMeshes = [];
  27524. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  27525. var subMesh = this.subMeshes[subIndex];
  27526. serializationObject.subMeshes.push({
  27527. materialIndex: subMesh.materialIndex,
  27528. verticesStart: subMesh.verticesStart,
  27529. verticesCount: subMesh.verticesCount,
  27530. indexStart: subMesh.indexStart,
  27531. indexCount: subMesh.indexCount
  27532. });
  27533. }
  27534. }
  27535. // Material
  27536. if (this.material) {
  27537. serializationObject.materialId = this.material.id;
  27538. }
  27539. else {
  27540. this.material = null;
  27541. }
  27542. // Morph targets
  27543. if (this.morphTargetManager) {
  27544. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  27545. }
  27546. // Skeleton
  27547. if (this.skeleton) {
  27548. serializationObject.skeletonId = this.skeleton.id;
  27549. }
  27550. // Physics
  27551. //TODO implement correct serialization for physics impostors.
  27552. var impostor = this.getPhysicsImpostor();
  27553. if (impostor) {
  27554. serializationObject.physicsMass = impostor.getParam("mass");
  27555. serializationObject.physicsFriction = impostor.getParam("friction");
  27556. serializationObject.physicsRestitution = impostor.getParam("mass");
  27557. serializationObject.physicsImpostor = impostor.type;
  27558. }
  27559. // Metadata
  27560. if (this.metadata) {
  27561. serializationObject.metadata = this.metadata;
  27562. }
  27563. // Instances
  27564. serializationObject.instances = [];
  27565. for (var index = 0; index < this.instances.length; index++) {
  27566. var instance = this.instances[index];
  27567. var serializationInstance = {
  27568. name: instance.name,
  27569. id: instance.id,
  27570. position: instance.position.asArray(),
  27571. scaling: instance.scaling.asArray()
  27572. };
  27573. if (instance.rotationQuaternion) {
  27574. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  27575. }
  27576. else if (instance.rotation) {
  27577. serializationInstance.rotation = instance.rotation.asArray();
  27578. }
  27579. serializationObject.instances.push(serializationInstance);
  27580. // Animations
  27581. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  27582. serializationInstance.ranges = instance.serializeAnimationRanges();
  27583. }
  27584. //
  27585. // Animations
  27586. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  27587. serializationObject.ranges = this.serializeAnimationRanges();
  27588. // Layer mask
  27589. serializationObject.layerMask = this.layerMask;
  27590. // Alpha
  27591. serializationObject.alphaIndex = this.alphaIndex;
  27592. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  27593. // Overlay
  27594. serializationObject.overlayAlpha = this.overlayAlpha;
  27595. serializationObject.overlayColor = this.overlayColor.asArray();
  27596. serializationObject.renderOverlay = this.renderOverlay;
  27597. // Fog
  27598. serializationObject.applyFog = this.applyFog;
  27599. // Action Manager
  27600. if (this.actionManager) {
  27601. serializationObject.actions = this.actionManager.serialize(this.name);
  27602. }
  27603. };
  27604. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  27605. if (!this.geometry) {
  27606. return;
  27607. }
  27608. this._markSubMeshesAsAttributesDirty();
  27609. var morphTargetManager = this._morphTargetManager;
  27610. if (morphTargetManager && morphTargetManager.vertexCount) {
  27611. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  27612. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  27613. this.morphTargetManager = null;
  27614. return;
  27615. }
  27616. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  27617. var morphTarget = morphTargetManager.getActiveTarget(index);
  27618. var positions = morphTarget.getPositions();
  27619. if (!positions) {
  27620. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  27621. return;
  27622. }
  27623. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  27624. var normals = morphTarget.getNormals();
  27625. if (normals) {
  27626. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  27627. }
  27628. var tangents = morphTarget.getTangents();
  27629. if (tangents) {
  27630. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  27631. }
  27632. }
  27633. }
  27634. else {
  27635. var index = 0;
  27636. // Positions
  27637. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  27638. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  27639. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  27640. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  27641. }
  27642. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  27643. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  27644. }
  27645. index++;
  27646. }
  27647. }
  27648. };
  27649. // Statics
  27650. /**
  27651. * Returns a new Mesh object parsed from the source provided.
  27652. * The parameter `parsedMesh` is the source.
  27653. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  27654. */
  27655. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  27656. var mesh;
  27657. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  27658. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  27659. }
  27660. else {
  27661. mesh = new Mesh(parsedMesh.name, scene);
  27662. }
  27663. mesh.id = parsedMesh.id;
  27664. if (BABYLON.Tags) {
  27665. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  27666. }
  27667. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  27668. if (parsedMesh.metadata !== undefined) {
  27669. mesh.metadata = parsedMesh.metadata;
  27670. }
  27671. if (parsedMesh.rotationQuaternion) {
  27672. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  27673. }
  27674. else if (parsedMesh.rotation) {
  27675. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  27676. }
  27677. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  27678. if (parsedMesh.localMatrix) {
  27679. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  27680. }
  27681. else if (parsedMesh.pivotMatrix) {
  27682. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  27683. }
  27684. mesh.setEnabled(parsedMesh.isEnabled);
  27685. mesh.isVisible = parsedMesh.isVisible;
  27686. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  27687. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  27688. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  27689. if (parsedMesh.applyFog !== undefined) {
  27690. mesh.applyFog = parsedMesh.applyFog;
  27691. }
  27692. if (parsedMesh.pickable !== undefined) {
  27693. mesh.isPickable = parsedMesh.pickable;
  27694. }
  27695. if (parsedMesh.alphaIndex !== undefined) {
  27696. mesh.alphaIndex = parsedMesh.alphaIndex;
  27697. }
  27698. mesh.receiveShadows = parsedMesh.receiveShadows;
  27699. mesh.billboardMode = parsedMesh.billboardMode;
  27700. if (parsedMesh.visibility !== undefined) {
  27701. mesh.visibility = parsedMesh.visibility;
  27702. }
  27703. mesh.checkCollisions = parsedMesh.checkCollisions;
  27704. if (parsedMesh.isBlocker !== undefined) {
  27705. mesh.isBlocker = parsedMesh.isBlocker;
  27706. }
  27707. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  27708. // freezeWorldMatrix
  27709. if (parsedMesh.freezeWorldMatrix) {
  27710. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  27711. }
  27712. // Parent
  27713. if (parsedMesh.parentId) {
  27714. mesh._waitingParentId = parsedMesh.parentId;
  27715. }
  27716. // Actions
  27717. if (parsedMesh.actions !== undefined) {
  27718. mesh._waitingActions = parsedMesh.actions;
  27719. }
  27720. // Overlay
  27721. if (parsedMesh.overlayAlpha !== undefined) {
  27722. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  27723. }
  27724. if (parsedMesh.overlayColor !== undefined) {
  27725. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  27726. }
  27727. if (parsedMesh.renderOverlay !== undefined) {
  27728. mesh.renderOverlay = parsedMesh.renderOverlay;
  27729. }
  27730. // Geometry
  27731. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  27732. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  27733. if (parsedMesh.delayLoadingFile) {
  27734. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27735. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  27736. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  27737. if (parsedMesh._binaryInfo) {
  27738. mesh._binaryInfo = parsedMesh._binaryInfo;
  27739. }
  27740. mesh._delayInfo = [];
  27741. if (parsedMesh.hasUVs) {
  27742. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  27743. }
  27744. if (parsedMesh.hasUVs2) {
  27745. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  27746. }
  27747. if (parsedMesh.hasUVs3) {
  27748. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  27749. }
  27750. if (parsedMesh.hasUVs4) {
  27751. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  27752. }
  27753. if (parsedMesh.hasUVs5) {
  27754. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  27755. }
  27756. if (parsedMesh.hasUVs6) {
  27757. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  27758. }
  27759. if (parsedMesh.hasColors) {
  27760. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  27761. }
  27762. if (parsedMesh.hasMatricesIndices) {
  27763. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27764. }
  27765. if (parsedMesh.hasMatricesWeights) {
  27766. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27767. }
  27768. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  27769. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  27770. mesh._checkDelayState();
  27771. }
  27772. }
  27773. else {
  27774. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  27775. }
  27776. // Material
  27777. if (parsedMesh.materialId) {
  27778. mesh.setMaterialByID(parsedMesh.materialId);
  27779. }
  27780. else {
  27781. mesh.material = null;
  27782. }
  27783. // Morph targets
  27784. if (parsedMesh.morphTargetManagerId > -1) {
  27785. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  27786. }
  27787. // Skeleton
  27788. if (parsedMesh.skeletonId > -1) {
  27789. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  27790. if (parsedMesh.numBoneInfluencers) {
  27791. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  27792. }
  27793. }
  27794. // Animations
  27795. if (parsedMesh.animations) {
  27796. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  27797. var parsedAnimation = parsedMesh.animations[animationIndex];
  27798. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27799. }
  27800. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  27801. }
  27802. if (parsedMesh.autoAnimate) {
  27803. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  27804. }
  27805. // Layer Mask
  27806. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  27807. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  27808. }
  27809. else {
  27810. mesh.layerMask = 0x0FFFFFFF;
  27811. }
  27812. // Physics
  27813. if (parsedMesh.physicsImpostor) {
  27814. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  27815. mass: parsedMesh.physicsMass,
  27816. friction: parsedMesh.physicsFriction,
  27817. restitution: parsedMesh.physicsRestitution
  27818. }, scene);
  27819. }
  27820. // Instances
  27821. if (parsedMesh.instances) {
  27822. for (var index = 0; index < parsedMesh.instances.length; index++) {
  27823. var parsedInstance = parsedMesh.instances[index];
  27824. var instance = mesh.createInstance(parsedInstance.name);
  27825. if (parsedInstance.id) {
  27826. instance.id = parsedInstance.id;
  27827. }
  27828. if (BABYLON.Tags) {
  27829. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  27830. }
  27831. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  27832. if (parsedInstance.parentId) {
  27833. instance._waitingParentId = parsedInstance.parentId;
  27834. }
  27835. if (parsedInstance.rotationQuaternion) {
  27836. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  27837. }
  27838. else if (parsedInstance.rotation) {
  27839. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  27840. }
  27841. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  27842. instance.checkCollisions = mesh.checkCollisions;
  27843. if (parsedMesh.animations) {
  27844. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  27845. parsedAnimation = parsedMesh.animations[animationIndex];
  27846. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27847. }
  27848. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  27849. }
  27850. }
  27851. }
  27852. return mesh;
  27853. };
  27854. /**
  27855. * Creates a ribbon mesh.
  27856. * Please consider using the same method from the MeshBuilder class instead.
  27857. * 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.
  27858. *
  27859. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  27860. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  27861. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  27862. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  27863. * 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.
  27864. * 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.
  27865. * 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
  27866. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27867. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27868. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27869. */
  27870. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  27871. if (closeArray === void 0) { closeArray = false; }
  27872. if (updatable === void 0) { updatable = false; }
  27873. return BABYLON.MeshBuilder.CreateRibbon(name, {
  27874. pathArray: pathArray,
  27875. closeArray: closeArray,
  27876. closePath: closePath,
  27877. offset: offset,
  27878. updatable: updatable,
  27879. sideOrientation: sideOrientation,
  27880. instance: instance
  27881. }, scene);
  27882. };
  27883. /**
  27884. * Creates a plane polygonal mesh. By default, this is a disc.
  27885. * Please consider using the same method from the MeshBuilder class instead.
  27886. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  27887. * 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.
  27888. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27889. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27890. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27891. */
  27892. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  27893. if (scene === void 0) { scene = null; }
  27894. var options = {
  27895. radius: radius,
  27896. tessellation: tessellation,
  27897. sideOrientation: sideOrientation,
  27898. updatable: updatable
  27899. };
  27900. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  27901. };
  27902. /**
  27903. * Creates a box mesh.
  27904. * Please consider using the same method from the MeshBuilder class instead.
  27905. * The parameter `size` sets the size (float) of each box side (default 1).
  27906. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27907. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27908. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27909. */
  27910. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  27911. if (scene === void 0) { scene = null; }
  27912. var options = {
  27913. size: size,
  27914. sideOrientation: sideOrientation,
  27915. updatable: updatable
  27916. };
  27917. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  27918. };
  27919. /**
  27920. * Creates a sphere mesh.
  27921. * Please consider using the same method from the MeshBuilder class instead.
  27922. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  27923. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  27924. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27925. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27926. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27927. */
  27928. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  27929. var options = {
  27930. segments: segments,
  27931. diameterX: diameter,
  27932. diameterY: diameter,
  27933. diameterZ: diameter,
  27934. sideOrientation: sideOrientation,
  27935. updatable: updatable
  27936. };
  27937. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  27938. };
  27939. /**
  27940. * Creates a cylinder or a cone mesh.
  27941. * Please consider using the same method from the MeshBuilder class instead.
  27942. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  27943. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  27944. * 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.
  27945. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  27946. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  27947. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27948. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27949. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27950. */
  27951. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  27952. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  27953. if (scene !== undefined) {
  27954. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  27955. updatable = scene;
  27956. }
  27957. scene = subdivisions;
  27958. subdivisions = 1;
  27959. }
  27960. var options = {
  27961. height: height,
  27962. diameterTop: diameterTop,
  27963. diameterBottom: diameterBottom,
  27964. tessellation: tessellation,
  27965. subdivisions: subdivisions,
  27966. sideOrientation: sideOrientation,
  27967. updatable: updatable
  27968. };
  27969. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  27970. };
  27971. // Torus (Code from SharpDX.org)
  27972. /**
  27973. * Creates a torus mesh.
  27974. * Please consider using the same method from the MeshBuilder class instead.
  27975. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  27976. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  27977. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  27978. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27979. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27980. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27981. */
  27982. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  27983. var options = {
  27984. diameter: diameter,
  27985. thickness: thickness,
  27986. tessellation: tessellation,
  27987. sideOrientation: sideOrientation,
  27988. updatable: updatable
  27989. };
  27990. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  27991. };
  27992. /**
  27993. * Creates a torus knot mesh.
  27994. * Please consider using the same method from the MeshBuilder class instead.
  27995. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  27996. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  27997. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  27998. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  27999. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28000. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28001. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28002. */
  28003. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  28004. var options = {
  28005. radius: radius,
  28006. tube: tube,
  28007. radialSegments: radialSegments,
  28008. tubularSegments: tubularSegments,
  28009. p: p,
  28010. q: q,
  28011. sideOrientation: sideOrientation,
  28012. updatable: updatable
  28013. };
  28014. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  28015. };
  28016. /**
  28017. * Creates a line mesh.
  28018. * Please consider using the same method from the MeshBuilder class instead.
  28019. * 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.
  28020. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  28021. * The parameter `points` is an array successive Vector3.
  28022. * 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
  28023. * When updating an instance, remember that only point positions can change, not the number of points.
  28024. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28025. */
  28026. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  28027. if (scene === void 0) { scene = null; }
  28028. if (updatable === void 0) { updatable = false; }
  28029. if (instance === void 0) { instance = null; }
  28030. var options = {
  28031. points: points,
  28032. updatable: updatable,
  28033. instance: instance
  28034. };
  28035. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  28036. };
  28037. /**
  28038. * Creates a dashed line mesh.
  28039. * Please consider using the same method from the MeshBuilder class instead.
  28040. * 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.
  28041. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  28042. * The parameter `points` is an array successive Vector3.
  28043. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  28044. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  28045. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  28046. * 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
  28047. * When updating an instance, remember that only point positions can change, not the number of points.
  28048. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28049. */
  28050. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  28051. if (scene === void 0) { scene = null; }
  28052. var options = {
  28053. points: points,
  28054. dashSize: dashSize,
  28055. gapSize: gapSize,
  28056. dashNb: dashNb,
  28057. updatable: updatable,
  28058. instance: instance
  28059. };
  28060. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  28061. };
  28062. /**
  28063. * Creates a polygon mesh.
  28064. * Please consider using the same method from the MeshBuilder class instead.
  28065. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  28066. * 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.
  28067. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28068. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28069. * Remember you can only change the shape positions, not their number when updating a polygon.
  28070. */
  28071. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  28072. var options = {
  28073. shape: shape,
  28074. holes: holes,
  28075. updatable: updatable,
  28076. sideOrientation: sideOrientation
  28077. };
  28078. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  28079. };
  28080. /**
  28081. * Creates an extruded polygon mesh, with depth in the Y direction.
  28082. * Please consider using the same method from the MeshBuilder class instead.
  28083. */
  28084. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  28085. var options = {
  28086. shape: shape,
  28087. holes: holes,
  28088. depth: depth,
  28089. updatable: updatable,
  28090. sideOrientation: sideOrientation
  28091. };
  28092. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  28093. };
  28094. /**
  28095. * Creates an extruded shape mesh.
  28096. * 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.
  28097. * Please consider using the same method from the MeshBuilder class instead.
  28098. *
  28099. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  28100. * 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
  28101. * extruded along the Z axis.
  28102. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  28103. * 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.
  28104. * The parameter `scale` (float, default 1) is the value to scale the shape.
  28105. * 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
  28106. * 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
  28107. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  28108. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28109. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28110. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28111. */
  28112. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  28113. if (scene === void 0) { scene = null; }
  28114. var options = {
  28115. shape: shape,
  28116. path: path,
  28117. scale: scale,
  28118. rotation: rotation,
  28119. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  28120. sideOrientation: sideOrientation,
  28121. instance: instance,
  28122. updatable: updatable
  28123. };
  28124. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  28125. };
  28126. /**
  28127. * Creates an custom extruded shape mesh.
  28128. * 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.
  28129. * Please consider using the same method from the MeshBuilder class instead.
  28130. *
  28131. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  28132. * 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
  28133. * extruded along the Z axis.
  28134. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  28135. * 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
  28136. * and the distance of this point from the begining of the path :
  28137. * ```javascript
  28138. * var rotationFunction = function(i, distance) {
  28139. * // do things
  28140. * return rotationValue; }
  28141. * ```
  28142. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  28143. * 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
  28144. * and the distance of this point from the begining of the path :
  28145. * ```javascript
  28146. * var scaleFunction = function(i, distance) {
  28147. * // do things
  28148. * return scaleValue;}
  28149. * ```
  28150. * It must returns a float value that will be the scale value applied to the shape on each path point.
  28151. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  28152. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  28153. * 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
  28154. * 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
  28155. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  28156. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28157. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28158. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28159. */
  28160. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  28161. var options = {
  28162. shape: shape,
  28163. path: path,
  28164. scaleFunction: scaleFunction,
  28165. rotationFunction: rotationFunction,
  28166. ribbonCloseArray: ribbonCloseArray,
  28167. ribbonClosePath: ribbonClosePath,
  28168. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  28169. sideOrientation: sideOrientation,
  28170. instance: instance,
  28171. updatable: updatable
  28172. };
  28173. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  28174. };
  28175. /**
  28176. * Creates lathe mesh.
  28177. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  28178. * Please consider using the same method from the MeshBuilder class instead.
  28179. * 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
  28180. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  28181. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  28182. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  28183. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28184. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28185. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28186. */
  28187. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  28188. var options = {
  28189. shape: shape,
  28190. radius: radius,
  28191. tessellation: tessellation,
  28192. sideOrientation: sideOrientation,
  28193. updatable: updatable
  28194. };
  28195. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  28196. };
  28197. /**
  28198. * Creates a plane mesh.
  28199. * Please consider using the same method from the MeshBuilder class instead.
  28200. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  28201. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28202. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28203. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28204. */
  28205. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  28206. var options = {
  28207. size: size,
  28208. width: size,
  28209. height: size,
  28210. sideOrientation: sideOrientation,
  28211. updatable: updatable
  28212. };
  28213. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  28214. };
  28215. /**
  28216. * Creates a ground mesh.
  28217. * Please consider using the same method from the MeshBuilder class instead.
  28218. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  28219. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  28220. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28221. */
  28222. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  28223. var options = {
  28224. width: width,
  28225. height: height,
  28226. subdivisions: subdivisions,
  28227. updatable: updatable
  28228. };
  28229. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  28230. };
  28231. /**
  28232. * Creates a tiled ground mesh.
  28233. * Please consider using the same method from the MeshBuilder class instead.
  28234. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  28235. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  28236. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  28237. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  28238. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  28239. * numbers of subdivisions on the ground width and height of each tile.
  28240. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28241. */
  28242. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  28243. var options = {
  28244. xmin: xmin,
  28245. zmin: zmin,
  28246. xmax: xmax,
  28247. zmax: zmax,
  28248. subdivisions: subdivisions,
  28249. precision: precision,
  28250. updatable: updatable
  28251. };
  28252. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  28253. };
  28254. /**
  28255. * Creates a ground mesh from a height map.
  28256. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  28257. * Please consider using the same method from the MeshBuilder class instead.
  28258. * The parameter `url` sets the URL of the height map image resource.
  28259. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  28260. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  28261. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  28262. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  28263. * 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).
  28264. * This function is passed the newly built mesh :
  28265. * ```javascript
  28266. * function(mesh) { // do things
  28267. * return; }
  28268. * ```
  28269. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28270. */
  28271. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  28272. var options = {
  28273. width: width,
  28274. height: height,
  28275. subdivisions: subdivisions,
  28276. minHeight: minHeight,
  28277. maxHeight: maxHeight,
  28278. updatable: updatable,
  28279. onReady: onReady
  28280. };
  28281. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  28282. };
  28283. /**
  28284. * Creates a tube mesh.
  28285. * 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.
  28286. * Please consider using the same method from the MeshBuilder class instead.
  28287. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  28288. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  28289. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  28290. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  28291. * 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.
  28292. * It must return a radius value (positive float) :
  28293. * ```javascript
  28294. * var radiusFunction = function(i, distance) {
  28295. * // do things
  28296. * return radius; }
  28297. * ```
  28298. * 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
  28299. * 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
  28300. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28301. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28302. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28303. */
  28304. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  28305. var options = {
  28306. path: path,
  28307. radius: radius,
  28308. tessellation: tessellation,
  28309. radiusFunction: radiusFunction,
  28310. arc: 1,
  28311. cap: cap,
  28312. updatable: updatable,
  28313. sideOrientation: sideOrientation,
  28314. instance: instance
  28315. };
  28316. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  28317. };
  28318. /**
  28319. * Creates a polyhedron mesh.
  28320. * Please consider using the same method from the MeshBuilder class instead.
  28321. * 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
  28322. * to choose the wanted type.
  28323. * The parameter `size` (positive float, default 1) sets the polygon size.
  28324. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  28325. * 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`.
  28326. * 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
  28327. * 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)`).
  28328. * 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
  28329. * 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.
  28330. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28331. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28332. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28333. */
  28334. Mesh.CreatePolyhedron = function (name, options, scene) {
  28335. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  28336. };
  28337. /**
  28338. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  28339. * Please consider using the same method from the MeshBuilder class instead.
  28340. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  28341. * 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`).
  28342. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  28343. * 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.
  28344. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28345. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28346. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28347. */
  28348. Mesh.CreateIcoSphere = function (name, options, scene) {
  28349. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  28350. };
  28351. /**
  28352. * Creates a decal mesh.
  28353. * Please consider using the same method from the MeshBuilder class instead.
  28354. * 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.
  28355. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  28356. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  28357. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  28358. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  28359. */
  28360. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  28361. var options = {
  28362. position: position,
  28363. normal: normal,
  28364. size: size,
  28365. angle: angle
  28366. };
  28367. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  28368. };
  28369. // Skeletons
  28370. /**
  28371. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  28372. */
  28373. Mesh.prototype.setPositionsForCPUSkinning = function () {
  28374. if (!this._sourcePositions) {
  28375. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28376. if (!source) {
  28377. return this._sourcePositions;
  28378. }
  28379. this._sourcePositions = new Float32Array(source);
  28380. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  28381. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  28382. }
  28383. }
  28384. return this._sourcePositions;
  28385. };
  28386. /**
  28387. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  28388. */
  28389. Mesh.prototype.setNormalsForCPUSkinning = function () {
  28390. if (!this._sourceNormals) {
  28391. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28392. if (!source) {
  28393. return this._sourceNormals;
  28394. }
  28395. this._sourceNormals = new Float32Array(source);
  28396. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  28397. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  28398. }
  28399. }
  28400. return this._sourceNormals;
  28401. };
  28402. /**
  28403. * Updates the vertex buffer by applying transformation from the bones.
  28404. * Returns the Mesh.
  28405. *
  28406. * @param {skeleton} skeleton to apply
  28407. */
  28408. Mesh.prototype.applySkeleton = function (skeleton) {
  28409. if (!this.geometry) {
  28410. return this;
  28411. }
  28412. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  28413. return this;
  28414. }
  28415. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  28416. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28417. return this;
  28418. }
  28419. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28420. return this;
  28421. }
  28422. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  28423. return this;
  28424. }
  28425. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  28426. return this;
  28427. }
  28428. if (!this._sourcePositions) {
  28429. var submeshes = this.subMeshes.slice();
  28430. this.setPositionsForCPUSkinning();
  28431. this.subMeshes = submeshes;
  28432. }
  28433. if (!this._sourceNormals) {
  28434. this.setNormalsForCPUSkinning();
  28435. }
  28436. // positionsData checks for not being Float32Array will only pass at most once
  28437. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28438. if (!positionsData) {
  28439. return this;
  28440. }
  28441. if (!(positionsData instanceof Float32Array)) {
  28442. positionsData = new Float32Array(positionsData);
  28443. }
  28444. // normalsData checks for not being Float32Array will only pass at most once
  28445. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28446. if (!normalsData) {
  28447. return this;
  28448. }
  28449. if (!(normalsData instanceof Float32Array)) {
  28450. normalsData = new Float32Array(normalsData);
  28451. }
  28452. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  28453. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  28454. if (!matricesWeightsData || !matricesIndicesData) {
  28455. return this;
  28456. }
  28457. var needExtras = this.numBoneInfluencers > 4;
  28458. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  28459. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  28460. var skeletonMatrices = skeleton.getTransformMatrices(this);
  28461. var tempVector3 = BABYLON.Vector3.Zero();
  28462. var finalMatrix = new BABYLON.Matrix();
  28463. var tempMatrix = new BABYLON.Matrix();
  28464. var matWeightIdx = 0;
  28465. var inf;
  28466. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  28467. var weight;
  28468. for (inf = 0; inf < 4; inf++) {
  28469. weight = matricesWeightsData[matWeightIdx + inf];
  28470. if (weight > 0) {
  28471. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  28472. finalMatrix.addToSelf(tempMatrix);
  28473. }
  28474. else
  28475. break;
  28476. }
  28477. if (needExtras) {
  28478. for (inf = 0; inf < 4; inf++) {
  28479. weight = matricesWeightsExtraData[matWeightIdx + inf];
  28480. if (weight > 0) {
  28481. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  28482. finalMatrix.addToSelf(tempMatrix);
  28483. }
  28484. else
  28485. break;
  28486. }
  28487. }
  28488. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  28489. tempVector3.toArray(positionsData, index);
  28490. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  28491. tempVector3.toArray(normalsData, index);
  28492. finalMatrix.reset();
  28493. }
  28494. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  28495. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  28496. return this;
  28497. };
  28498. // Tools
  28499. /**
  28500. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  28501. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  28502. */
  28503. Mesh.MinMax = function (meshes) {
  28504. var minVector = null;
  28505. var maxVector = null;
  28506. meshes.forEach(function (mesh, index, array) {
  28507. var boundingInfo = mesh.getBoundingInfo();
  28508. var boundingBox = boundingInfo.boundingBox;
  28509. if (!minVector || !maxVector) {
  28510. minVector = boundingBox.minimumWorld;
  28511. maxVector = boundingBox.maximumWorld;
  28512. }
  28513. else {
  28514. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  28515. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  28516. }
  28517. });
  28518. if (!minVector || !maxVector) {
  28519. return {
  28520. min: BABYLON.Vector3.Zero(),
  28521. max: BABYLON.Vector3.Zero()
  28522. };
  28523. }
  28524. return {
  28525. min: minVector,
  28526. max: maxVector
  28527. };
  28528. };
  28529. /**
  28530. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  28531. */
  28532. Mesh.Center = function (meshesOrMinMaxVector) {
  28533. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  28534. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  28535. };
  28536. /**
  28537. * Merge the array of meshes into a single mesh for performance reasons.
  28538. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  28539. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  28540. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  28541. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  28542. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  28543. */
  28544. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  28545. if (disposeSource === void 0) { disposeSource = true; }
  28546. var index;
  28547. if (!allow32BitsIndices) {
  28548. var totalVertices = 0;
  28549. // Counting vertices
  28550. for (index = 0; index < meshes.length; index++) {
  28551. if (meshes[index]) {
  28552. totalVertices += meshes[index].getTotalVertices();
  28553. if (totalVertices > 65536) {
  28554. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  28555. return null;
  28556. }
  28557. }
  28558. }
  28559. }
  28560. // Merge
  28561. var vertexData = null;
  28562. var otherVertexData;
  28563. var indiceArray = new Array();
  28564. var source = null;
  28565. for (index = 0; index < meshes.length; index++) {
  28566. if (meshes[index]) {
  28567. meshes[index].computeWorldMatrix(true);
  28568. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  28569. otherVertexData.transform(meshes[index].getWorldMatrix());
  28570. if (vertexData) {
  28571. vertexData.merge(otherVertexData);
  28572. }
  28573. else {
  28574. vertexData = otherVertexData;
  28575. source = meshes[index];
  28576. }
  28577. if (subdivideWithSubMeshes) {
  28578. indiceArray.push(meshes[index].getTotalIndices());
  28579. }
  28580. }
  28581. }
  28582. source = source;
  28583. if (!meshSubclass) {
  28584. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  28585. }
  28586. vertexData.applyToMesh(meshSubclass);
  28587. // Setting properties
  28588. meshSubclass.material = source.material;
  28589. meshSubclass.checkCollisions = source.checkCollisions;
  28590. // Cleaning
  28591. if (disposeSource) {
  28592. for (index = 0; index < meshes.length; index++) {
  28593. if (meshes[index]) {
  28594. meshes[index].dispose();
  28595. }
  28596. }
  28597. }
  28598. // Subdivide
  28599. if (subdivideWithSubMeshes) {
  28600. //-- Suppresions du submesh global
  28601. meshSubclass.releaseSubMeshes();
  28602. index = 0;
  28603. var offset = 0;
  28604. //-- aplique la subdivision en fonction du tableau d'indices
  28605. while (index < indiceArray.length) {
  28606. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  28607. offset += indiceArray[index];
  28608. index++;
  28609. }
  28610. }
  28611. return meshSubclass;
  28612. };
  28613. // Consts
  28614. Mesh._FRONTSIDE = 0;
  28615. Mesh._BACKSIDE = 1;
  28616. Mesh._DOUBLESIDE = 2;
  28617. Mesh._DEFAULTSIDE = 0;
  28618. Mesh._NO_CAP = 0;
  28619. Mesh._CAP_START = 1;
  28620. Mesh._CAP_END = 2;
  28621. Mesh._CAP_ALL = 3;
  28622. return Mesh;
  28623. }(BABYLON.AbstractMesh));
  28624. BABYLON.Mesh = Mesh;
  28625. })(BABYLON || (BABYLON = {}));
  28626. //# sourceMappingURL=babylon.mesh.js.map
  28627. var BABYLON;
  28628. (function (BABYLON) {
  28629. var BaseSubMesh = /** @class */ (function () {
  28630. function BaseSubMesh() {
  28631. }
  28632. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  28633. get: function () {
  28634. return this._materialEffect;
  28635. },
  28636. enumerable: true,
  28637. configurable: true
  28638. });
  28639. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  28640. if (defines === void 0) { defines = null; }
  28641. if (this._materialEffect === effect) {
  28642. if (!effect) {
  28643. this._materialDefines = null;
  28644. }
  28645. return;
  28646. }
  28647. this._materialDefines = defines;
  28648. this._materialEffect = effect;
  28649. };
  28650. return BaseSubMesh;
  28651. }());
  28652. BABYLON.BaseSubMesh = BaseSubMesh;
  28653. var SubMesh = /** @class */ (function (_super) {
  28654. __extends(SubMesh, _super);
  28655. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  28656. if (createBoundingBox === void 0) { createBoundingBox = true; }
  28657. var _this = _super.call(this) || this;
  28658. _this.materialIndex = materialIndex;
  28659. _this.verticesStart = verticesStart;
  28660. _this.verticesCount = verticesCount;
  28661. _this.indexStart = indexStart;
  28662. _this.indexCount = indexCount;
  28663. _this._renderId = 0;
  28664. _this._mesh = mesh;
  28665. _this._renderingMesh = renderingMesh || mesh;
  28666. mesh.subMeshes.push(_this);
  28667. _this._trianglePlanes = [];
  28668. _this._id = mesh.subMeshes.length - 1;
  28669. if (createBoundingBox) {
  28670. _this.refreshBoundingInfo();
  28671. mesh.computeWorldMatrix(true);
  28672. }
  28673. return _this;
  28674. }
  28675. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  28676. if (createBoundingBox === void 0) { createBoundingBox = true; }
  28677. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  28678. };
  28679. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  28680. get: function () {
  28681. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  28682. },
  28683. enumerable: true,
  28684. configurable: true
  28685. });
  28686. /**
  28687. * Returns the submesh BoudingInfo object.
  28688. */
  28689. SubMesh.prototype.getBoundingInfo = function () {
  28690. if (this.IsGlobal) {
  28691. return this._mesh.getBoundingInfo();
  28692. }
  28693. return this._boundingInfo;
  28694. };
  28695. /**
  28696. * Sets the submesh BoundingInfo.
  28697. * Return the SubMesh.
  28698. */
  28699. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  28700. this._boundingInfo = boundingInfo;
  28701. return this;
  28702. };
  28703. /**
  28704. * Returns the mesh of the current submesh.
  28705. */
  28706. SubMesh.prototype.getMesh = function () {
  28707. return this._mesh;
  28708. };
  28709. /**
  28710. * Returns the rendering mesh of the submesh.
  28711. */
  28712. SubMesh.prototype.getRenderingMesh = function () {
  28713. return this._renderingMesh;
  28714. };
  28715. /**
  28716. * Returns the submesh material.
  28717. */
  28718. SubMesh.prototype.getMaterial = function () {
  28719. var rootMaterial = this._renderingMesh.material;
  28720. if (rootMaterial === null || rootMaterial === undefined) {
  28721. return this._mesh.getScene().defaultMaterial;
  28722. }
  28723. else if (rootMaterial.getSubMaterial) {
  28724. var multiMaterial = rootMaterial;
  28725. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  28726. if (this._currentMaterial !== effectiveMaterial) {
  28727. this._currentMaterial = effectiveMaterial;
  28728. this._materialDefines = null;
  28729. }
  28730. return effectiveMaterial;
  28731. }
  28732. return rootMaterial;
  28733. };
  28734. // Methods
  28735. /**
  28736. * Sets a new updated BoundingInfo object to the submesh.
  28737. * Returns the SubMesh.
  28738. */
  28739. SubMesh.prototype.refreshBoundingInfo = function () {
  28740. this._lastColliderWorldVertices = null;
  28741. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  28742. return this;
  28743. }
  28744. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28745. if (!data) {
  28746. this._boundingInfo = this._mesh.getBoundingInfo();
  28747. return this;
  28748. }
  28749. var indices = this._renderingMesh.getIndices();
  28750. var extend;
  28751. //is this the only submesh?
  28752. if (this.indexStart === 0 && this.indexCount === indices.length) {
  28753. var boundingInfo = this._renderingMesh.getBoundingInfo();
  28754. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  28755. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  28756. }
  28757. else {
  28758. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  28759. }
  28760. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28761. return this;
  28762. };
  28763. SubMesh.prototype._checkCollision = function (collider) {
  28764. var boundingInfo = this._renderingMesh.getBoundingInfo();
  28765. return boundingInfo._checkCollision(collider);
  28766. };
  28767. /**
  28768. * Updates the submesh BoundingInfo.
  28769. * Returns the Submesh.
  28770. */
  28771. SubMesh.prototype.updateBoundingInfo = function (world) {
  28772. var boundingInfo = this.getBoundingInfo();
  28773. if (!boundingInfo) {
  28774. this.refreshBoundingInfo();
  28775. boundingInfo = this.getBoundingInfo();
  28776. }
  28777. boundingInfo.update(world);
  28778. return this;
  28779. };
  28780. /**
  28781. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  28782. * Boolean returned.
  28783. */
  28784. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  28785. var boundingInfo = this.getBoundingInfo();
  28786. if (!boundingInfo) {
  28787. return false;
  28788. }
  28789. return boundingInfo.isInFrustum(frustumPlanes);
  28790. };
  28791. /**
  28792. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  28793. * Boolean returned.
  28794. */
  28795. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  28796. var boundingInfo = this.getBoundingInfo();
  28797. if (!boundingInfo) {
  28798. return false;
  28799. }
  28800. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  28801. };
  28802. /**
  28803. * Renders the submesh.
  28804. * Returns it.
  28805. */
  28806. SubMesh.prototype.render = function (enableAlphaMode) {
  28807. this._renderingMesh.render(this, enableAlphaMode);
  28808. return this;
  28809. };
  28810. /**
  28811. * Returns a new Index Buffer.
  28812. * Type returned : WebGLBuffer.
  28813. */
  28814. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  28815. if (!this._linesIndexBuffer) {
  28816. var linesIndices = [];
  28817. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  28818. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  28819. }
  28820. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  28821. this.linesIndexCount = linesIndices.length;
  28822. }
  28823. return this._linesIndexBuffer;
  28824. };
  28825. /**
  28826. * True is the passed Ray intersects the submesh bounding box.
  28827. * Boolean returned.
  28828. */
  28829. SubMesh.prototype.canIntersects = function (ray) {
  28830. var boundingInfo = this.getBoundingInfo();
  28831. if (!boundingInfo) {
  28832. return false;
  28833. }
  28834. return ray.intersectsBox(boundingInfo.boundingBox);
  28835. };
  28836. /**
  28837. * Returns an object IntersectionInfo.
  28838. */
  28839. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  28840. var intersectInfo = null;
  28841. // LineMesh first as it's also a Mesh...
  28842. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  28843. var lineMesh = this._mesh;
  28844. // Line test
  28845. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  28846. var p0 = positions[indices[index]];
  28847. var p1 = positions[indices[index + 1]];
  28848. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  28849. if (length < 0) {
  28850. continue;
  28851. }
  28852. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  28853. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  28854. if (fastCheck) {
  28855. break;
  28856. }
  28857. }
  28858. }
  28859. }
  28860. else {
  28861. // Triangles test
  28862. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  28863. var p0 = positions[indices[index]];
  28864. var p1 = positions[indices[index + 1]];
  28865. var p2 = positions[indices[index + 2]];
  28866. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  28867. if (currentIntersectInfo) {
  28868. if (currentIntersectInfo.distance < 0) {
  28869. continue;
  28870. }
  28871. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  28872. intersectInfo = currentIntersectInfo;
  28873. intersectInfo.faceId = index / 3;
  28874. if (fastCheck) {
  28875. break;
  28876. }
  28877. }
  28878. }
  28879. }
  28880. }
  28881. return intersectInfo;
  28882. };
  28883. SubMesh.prototype._rebuild = function () {
  28884. if (this._linesIndexBuffer) {
  28885. this._linesIndexBuffer = null;
  28886. }
  28887. };
  28888. // Clone
  28889. /**
  28890. * Creates a new Submesh from the passed Mesh.
  28891. */
  28892. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  28893. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  28894. if (!this.IsGlobal) {
  28895. var boundingInfo = this.getBoundingInfo();
  28896. if (!boundingInfo) {
  28897. return result;
  28898. }
  28899. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  28900. }
  28901. return result;
  28902. };
  28903. // Dispose
  28904. /**
  28905. * Disposes the Submesh.
  28906. * Returns nothing.
  28907. */
  28908. SubMesh.prototype.dispose = function () {
  28909. if (this._linesIndexBuffer) {
  28910. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  28911. this._linesIndexBuffer = null;
  28912. }
  28913. // Remove from mesh
  28914. var index = this._mesh.subMeshes.indexOf(this);
  28915. this._mesh.subMeshes.splice(index, 1);
  28916. };
  28917. // Statics
  28918. /**
  28919. * Creates a new Submesh from the passed parameters :
  28920. * - materialIndex (integer) : the index of the main mesh material.
  28921. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  28922. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  28923. * - mesh (Mesh) : the main mesh to create the submesh from.
  28924. * - renderingMesh (optional Mesh) : rendering mesh.
  28925. */
  28926. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  28927. var minVertexIndex = Number.MAX_VALUE;
  28928. var maxVertexIndex = -Number.MAX_VALUE;
  28929. renderingMesh = (renderingMesh || mesh);
  28930. var indices = renderingMesh.getIndices();
  28931. for (var index = startIndex; index < startIndex + indexCount; index++) {
  28932. var vertexIndex = indices[index];
  28933. if (vertexIndex < minVertexIndex)
  28934. minVertexIndex = vertexIndex;
  28935. if (vertexIndex > maxVertexIndex)
  28936. maxVertexIndex = vertexIndex;
  28937. }
  28938. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  28939. };
  28940. return SubMesh;
  28941. }(BaseSubMesh));
  28942. BABYLON.SubMesh = SubMesh;
  28943. })(BABYLON || (BABYLON = {}));
  28944. //# sourceMappingURL=babylon.subMesh.js.map
  28945. var __assign = (this && this.__assign) || Object.assign || function(t) {
  28946. for (var s, i = 1, n = arguments.length; i < n; i++) {
  28947. s = arguments[i];
  28948. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  28949. t[p] = s[p];
  28950. }
  28951. return t;
  28952. };
  28953. var BABYLON;
  28954. (function (BABYLON) {
  28955. var MaterialDefines = /** @class */ (function () {
  28956. function MaterialDefines() {
  28957. this._isDirty = true;
  28958. this._areLightsDirty = true;
  28959. this._areAttributesDirty = true;
  28960. this._areTexturesDirty = true;
  28961. this._areFresnelDirty = true;
  28962. this._areMiscDirty = true;
  28963. this._areImageProcessingDirty = true;
  28964. this._normals = false;
  28965. this._uvs = false;
  28966. this._needNormals = false;
  28967. this._needUVs = false;
  28968. }
  28969. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  28970. get: function () {
  28971. return this._isDirty;
  28972. },
  28973. enumerable: true,
  28974. configurable: true
  28975. });
  28976. MaterialDefines.prototype.markAsProcessed = function () {
  28977. this._isDirty = false;
  28978. this._areAttributesDirty = false;
  28979. this._areTexturesDirty = false;
  28980. this._areFresnelDirty = false;
  28981. this._areLightsDirty = false;
  28982. this._areMiscDirty = false;
  28983. this._areImageProcessingDirty = false;
  28984. };
  28985. MaterialDefines.prototype.markAsUnprocessed = function () {
  28986. this._isDirty = true;
  28987. };
  28988. MaterialDefines.prototype.markAllAsDirty = function () {
  28989. this._areTexturesDirty = true;
  28990. this._areAttributesDirty = true;
  28991. this._areLightsDirty = true;
  28992. this._areFresnelDirty = true;
  28993. this._areMiscDirty = true;
  28994. this._areImageProcessingDirty = true;
  28995. this._isDirty = true;
  28996. };
  28997. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  28998. this._areImageProcessingDirty = true;
  28999. this._isDirty = true;
  29000. };
  29001. MaterialDefines.prototype.markAsLightDirty = function () {
  29002. this._areLightsDirty = true;
  29003. this._isDirty = true;
  29004. };
  29005. MaterialDefines.prototype.markAsAttributesDirty = function () {
  29006. this._areAttributesDirty = true;
  29007. this._isDirty = true;
  29008. };
  29009. MaterialDefines.prototype.markAsTexturesDirty = function () {
  29010. this._areTexturesDirty = true;
  29011. this._isDirty = true;
  29012. };
  29013. MaterialDefines.prototype.markAsFresnelDirty = function () {
  29014. this._areFresnelDirty = true;
  29015. this._isDirty = true;
  29016. };
  29017. MaterialDefines.prototype.markAsMiscDirty = function () {
  29018. this._areMiscDirty = true;
  29019. this._isDirty = true;
  29020. };
  29021. MaterialDefines.prototype.rebuild = function () {
  29022. if (this._keys) {
  29023. delete this._keys;
  29024. }
  29025. this._keys = [];
  29026. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  29027. var key = _a[_i];
  29028. if (key[0] === "_") {
  29029. continue;
  29030. }
  29031. this._keys.push(key);
  29032. }
  29033. };
  29034. MaterialDefines.prototype.isEqual = function (other) {
  29035. if (this._keys.length !== other._keys.length) {
  29036. return false;
  29037. }
  29038. for (var index = 0; index < this._keys.length; index++) {
  29039. var prop = this._keys[index];
  29040. if (this[prop] !== other[prop]) {
  29041. return false;
  29042. }
  29043. }
  29044. return true;
  29045. };
  29046. MaterialDefines.prototype.cloneTo = function (other) {
  29047. if (this._keys.length !== other._keys.length) {
  29048. other._keys = this._keys.slice(0);
  29049. }
  29050. for (var index = 0; index < this._keys.length; index++) {
  29051. var prop = this._keys[index];
  29052. other[prop] = this[prop];
  29053. }
  29054. };
  29055. MaterialDefines.prototype.reset = function () {
  29056. for (var index = 0; index < this._keys.length; index++) {
  29057. var prop = this._keys[index];
  29058. if (typeof (this[prop]) === "number") {
  29059. this[prop] = 0;
  29060. }
  29061. else {
  29062. this[prop] = false;
  29063. }
  29064. }
  29065. };
  29066. MaterialDefines.prototype.toString = function () {
  29067. var result = "";
  29068. for (var index = 0; index < this._keys.length; index++) {
  29069. var prop = this._keys[index];
  29070. var value = this[prop];
  29071. if (typeof (value) === "number") {
  29072. result += "#define " + prop + " " + this[prop] + "\n";
  29073. }
  29074. else if (value) {
  29075. result += "#define " + prop + "\n";
  29076. }
  29077. }
  29078. return result;
  29079. };
  29080. return MaterialDefines;
  29081. }());
  29082. BABYLON.MaterialDefines = MaterialDefines;
  29083. var Material = /** @class */ (function () {
  29084. function Material(name, scene, doNotAdd) {
  29085. this.checkReadyOnEveryCall = false;
  29086. this.checkReadyOnlyOnce = false;
  29087. this.state = "";
  29088. this._alpha = 1.0;
  29089. this._backFaceCulling = true;
  29090. this.doNotSerialize = false;
  29091. this.storeEffectOnSubMeshes = false;
  29092. /**
  29093. * An event triggered when the material is disposed.
  29094. * @type {BABYLON.Observable}
  29095. */
  29096. this.onDisposeObservable = new BABYLON.Observable();
  29097. /**
  29098. * An event triggered when the material is bound.
  29099. * @type {BABYLON.Observable}
  29100. */
  29101. this.onBindObservable = new BABYLON.Observable();
  29102. /**
  29103. * An event triggered when the material is unbound.
  29104. * @type {BABYLON.Observable}
  29105. */
  29106. this.onUnBindObservable = new BABYLON.Observable();
  29107. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  29108. this._needDepthPrePass = false;
  29109. this.disableDepthWrite = false;
  29110. this.forceDepthWrite = false;
  29111. this.separateCullingPass = false;
  29112. this._fogEnabled = true;
  29113. this.pointSize = 1.0;
  29114. this.zOffset = 0;
  29115. this._wasPreviouslyReady = false;
  29116. this._fillMode = Material.TriangleFillMode;
  29117. this.name = name;
  29118. this.id = name || BABYLON.Tools.RandomId();
  29119. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  29120. if (this._scene.useRightHandedSystem) {
  29121. this.sideOrientation = Material.ClockWiseSideOrientation;
  29122. }
  29123. else {
  29124. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  29125. }
  29126. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  29127. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  29128. if (!doNotAdd) {
  29129. this._scene.materials.push(this);
  29130. }
  29131. }
  29132. Object.defineProperty(Material, "TriangleFillMode", {
  29133. get: function () {
  29134. return Material._TriangleFillMode;
  29135. },
  29136. enumerable: true,
  29137. configurable: true
  29138. });
  29139. Object.defineProperty(Material, "WireFrameFillMode", {
  29140. get: function () {
  29141. return Material._WireFrameFillMode;
  29142. },
  29143. enumerable: true,
  29144. configurable: true
  29145. });
  29146. Object.defineProperty(Material, "PointFillMode", {
  29147. get: function () {
  29148. return Material._PointFillMode;
  29149. },
  29150. enumerable: true,
  29151. configurable: true
  29152. });
  29153. Object.defineProperty(Material, "PointListDrawMode", {
  29154. get: function () {
  29155. return Material._PointListDrawMode;
  29156. },
  29157. enumerable: true,
  29158. configurable: true
  29159. });
  29160. Object.defineProperty(Material, "LineListDrawMode", {
  29161. get: function () {
  29162. return Material._LineListDrawMode;
  29163. },
  29164. enumerable: true,
  29165. configurable: true
  29166. });
  29167. Object.defineProperty(Material, "LineLoopDrawMode", {
  29168. get: function () {
  29169. return Material._LineLoopDrawMode;
  29170. },
  29171. enumerable: true,
  29172. configurable: true
  29173. });
  29174. Object.defineProperty(Material, "LineStripDrawMode", {
  29175. get: function () {
  29176. return Material._LineStripDrawMode;
  29177. },
  29178. enumerable: true,
  29179. configurable: true
  29180. });
  29181. Object.defineProperty(Material, "TriangleStripDrawMode", {
  29182. get: function () {
  29183. return Material._TriangleStripDrawMode;
  29184. },
  29185. enumerable: true,
  29186. configurable: true
  29187. });
  29188. Object.defineProperty(Material, "TriangleFanDrawMode", {
  29189. get: function () {
  29190. return Material._TriangleFanDrawMode;
  29191. },
  29192. enumerable: true,
  29193. configurable: true
  29194. });
  29195. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  29196. get: function () {
  29197. return Material._ClockWiseSideOrientation;
  29198. },
  29199. enumerable: true,
  29200. configurable: true
  29201. });
  29202. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  29203. get: function () {
  29204. return Material._CounterClockWiseSideOrientation;
  29205. },
  29206. enumerable: true,
  29207. configurable: true
  29208. });
  29209. Object.defineProperty(Material, "TextureDirtyFlag", {
  29210. get: function () {
  29211. return Material._TextureDirtyFlag;
  29212. },
  29213. enumerable: true,
  29214. configurable: true
  29215. });
  29216. Object.defineProperty(Material, "LightDirtyFlag", {
  29217. get: function () {
  29218. return Material._LightDirtyFlag;
  29219. },
  29220. enumerable: true,
  29221. configurable: true
  29222. });
  29223. Object.defineProperty(Material, "FresnelDirtyFlag", {
  29224. get: function () {
  29225. return Material._FresnelDirtyFlag;
  29226. },
  29227. enumerable: true,
  29228. configurable: true
  29229. });
  29230. Object.defineProperty(Material, "AttributesDirtyFlag", {
  29231. get: function () {
  29232. return Material._AttributesDirtyFlag;
  29233. },
  29234. enumerable: true,
  29235. configurable: true
  29236. });
  29237. Object.defineProperty(Material, "MiscDirtyFlag", {
  29238. get: function () {
  29239. return Material._MiscDirtyFlag;
  29240. },
  29241. enumerable: true,
  29242. configurable: true
  29243. });
  29244. Object.defineProperty(Material.prototype, "alpha", {
  29245. get: function () {
  29246. return this._alpha;
  29247. },
  29248. set: function (value) {
  29249. if (this._alpha === value) {
  29250. return;
  29251. }
  29252. this._alpha = value;
  29253. this.markAsDirty(Material.MiscDirtyFlag);
  29254. },
  29255. enumerable: true,
  29256. configurable: true
  29257. });
  29258. Object.defineProperty(Material.prototype, "backFaceCulling", {
  29259. get: function () {
  29260. return this._backFaceCulling;
  29261. },
  29262. set: function (value) {
  29263. if (this._backFaceCulling === value) {
  29264. return;
  29265. }
  29266. this._backFaceCulling = value;
  29267. this.markAsDirty(Material.TextureDirtyFlag);
  29268. },
  29269. enumerable: true,
  29270. configurable: true
  29271. });
  29272. Object.defineProperty(Material.prototype, "onDispose", {
  29273. set: function (callback) {
  29274. if (this._onDisposeObserver) {
  29275. this.onDisposeObservable.remove(this._onDisposeObserver);
  29276. }
  29277. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  29278. },
  29279. enumerable: true,
  29280. configurable: true
  29281. });
  29282. Object.defineProperty(Material.prototype, "onBind", {
  29283. set: function (callback) {
  29284. if (this._onBindObserver) {
  29285. this.onBindObservable.remove(this._onBindObserver);
  29286. }
  29287. this._onBindObserver = this.onBindObservable.add(callback);
  29288. },
  29289. enumerable: true,
  29290. configurable: true
  29291. });
  29292. Object.defineProperty(Material.prototype, "alphaMode", {
  29293. get: function () {
  29294. return this._alphaMode;
  29295. },
  29296. set: function (value) {
  29297. if (this._alphaMode === value) {
  29298. return;
  29299. }
  29300. this._alphaMode = value;
  29301. this.markAsDirty(Material.TextureDirtyFlag);
  29302. },
  29303. enumerable: true,
  29304. configurable: true
  29305. });
  29306. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  29307. get: function () {
  29308. return this._needDepthPrePass;
  29309. },
  29310. set: function (value) {
  29311. if (this._needDepthPrePass === value) {
  29312. return;
  29313. }
  29314. this._needDepthPrePass = value;
  29315. if (this._needDepthPrePass) {
  29316. this.checkReadyOnEveryCall = true;
  29317. }
  29318. },
  29319. enumerable: true,
  29320. configurable: true
  29321. });
  29322. Object.defineProperty(Material.prototype, "fogEnabled", {
  29323. get: function () {
  29324. return this._fogEnabled;
  29325. },
  29326. set: function (value) {
  29327. if (this._fogEnabled === value) {
  29328. return;
  29329. }
  29330. this._fogEnabled = value;
  29331. this.markAsDirty(Material.MiscDirtyFlag);
  29332. },
  29333. enumerable: true,
  29334. configurable: true
  29335. });
  29336. Object.defineProperty(Material.prototype, "wireframe", {
  29337. get: function () {
  29338. return this._fillMode === Material.WireFrameFillMode;
  29339. },
  29340. set: function (value) {
  29341. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  29342. },
  29343. enumerable: true,
  29344. configurable: true
  29345. });
  29346. Object.defineProperty(Material.prototype, "pointsCloud", {
  29347. get: function () {
  29348. return this._fillMode === Material.PointFillMode;
  29349. },
  29350. set: function (value) {
  29351. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  29352. },
  29353. enumerable: true,
  29354. configurable: true
  29355. });
  29356. Object.defineProperty(Material.prototype, "fillMode", {
  29357. get: function () {
  29358. return this._fillMode;
  29359. },
  29360. set: function (value) {
  29361. if (this._fillMode === value) {
  29362. return;
  29363. }
  29364. this._fillMode = value;
  29365. this.markAsDirty(Material.MiscDirtyFlag);
  29366. },
  29367. enumerable: true,
  29368. configurable: true
  29369. });
  29370. /**
  29371. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  29372. * subclasses should override adding information pertainent to themselves
  29373. */
  29374. Material.prototype.toString = function (fullDetails) {
  29375. var ret = "Name: " + this.name;
  29376. if (fullDetails) {
  29377. }
  29378. return ret;
  29379. };
  29380. /**
  29381. * Child classes can use it to update shaders
  29382. */
  29383. Material.prototype.getClassName = function () {
  29384. return "Material";
  29385. };
  29386. Object.defineProperty(Material.prototype, "isFrozen", {
  29387. get: function () {
  29388. return this.checkReadyOnlyOnce;
  29389. },
  29390. enumerable: true,
  29391. configurable: true
  29392. });
  29393. Material.prototype.freeze = function () {
  29394. this.checkReadyOnlyOnce = true;
  29395. };
  29396. Material.prototype.unfreeze = function () {
  29397. this.checkReadyOnlyOnce = false;
  29398. };
  29399. Material.prototype.isReady = function (mesh, useInstances) {
  29400. return true;
  29401. };
  29402. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  29403. return false;
  29404. };
  29405. Material.prototype.getEffect = function () {
  29406. return this._effect;
  29407. };
  29408. Material.prototype.getScene = function () {
  29409. return this._scene;
  29410. };
  29411. Material.prototype.needAlphaBlending = function () {
  29412. return (this.alpha < 1.0);
  29413. };
  29414. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  29415. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  29416. };
  29417. Material.prototype.needAlphaTesting = function () {
  29418. return false;
  29419. };
  29420. Material.prototype.getAlphaTestTexture = function () {
  29421. return null;
  29422. };
  29423. Material.prototype.markDirty = function () {
  29424. this._wasPreviouslyReady = false;
  29425. };
  29426. Material.prototype._preBind = function (effect, overrideOrientation) {
  29427. if (overrideOrientation === void 0) { overrideOrientation = null; }
  29428. var engine = this._scene.getEngine();
  29429. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  29430. var reverse = orientation === Material.ClockWiseSideOrientation;
  29431. engine.enableEffect(effect ? effect : this._effect);
  29432. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  29433. return reverse;
  29434. };
  29435. Material.prototype.bind = function (world, mesh) {
  29436. };
  29437. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  29438. };
  29439. Material.prototype.bindOnlyWorldMatrix = function (world) {
  29440. };
  29441. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  29442. sceneUbo.bindToEffect(effect, "Scene");
  29443. };
  29444. Material.prototype.bindView = function (effect) {
  29445. if (!this._useUBO) {
  29446. effect.setMatrix("view", this.getScene().getViewMatrix());
  29447. }
  29448. else {
  29449. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  29450. }
  29451. };
  29452. Material.prototype.bindViewProjection = function (effect) {
  29453. if (!this._useUBO) {
  29454. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  29455. }
  29456. else {
  29457. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  29458. }
  29459. };
  29460. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  29461. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  29462. };
  29463. Material.prototype._afterBind = function (mesh) {
  29464. this._scene._cachedMaterial = this;
  29465. if (mesh) {
  29466. this._scene._cachedVisibility = mesh.visibility;
  29467. }
  29468. else {
  29469. this._scene._cachedVisibility = 1;
  29470. }
  29471. if (mesh) {
  29472. this.onBindObservable.notifyObservers(mesh);
  29473. }
  29474. if (this.disableDepthWrite) {
  29475. var engine = this._scene.getEngine();
  29476. this._cachedDepthWriteState = engine.getDepthWrite();
  29477. engine.setDepthWrite(false);
  29478. }
  29479. };
  29480. Material.prototype.unbind = function () {
  29481. this.onUnBindObservable.notifyObservers(this);
  29482. if (this.disableDepthWrite) {
  29483. var engine = this._scene.getEngine();
  29484. engine.setDepthWrite(this._cachedDepthWriteState);
  29485. }
  29486. };
  29487. Material.prototype.getActiveTextures = function () {
  29488. return [];
  29489. };
  29490. Material.prototype.hasTexture = function (texture) {
  29491. return false;
  29492. };
  29493. Material.prototype.clone = function (name) {
  29494. return null;
  29495. };
  29496. Material.prototype.getBindedMeshes = function () {
  29497. var result = new Array();
  29498. for (var index = 0; index < this._scene.meshes.length; index++) {
  29499. var mesh = this._scene.meshes[index];
  29500. if (mesh.material === this) {
  29501. result.push(mesh);
  29502. }
  29503. }
  29504. return result;
  29505. };
  29506. /**
  29507. * Force shader compilation including textures ready check
  29508. */
  29509. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  29510. var _this = this;
  29511. var localOptions = __assign({ clipPlane: false }, options);
  29512. var subMesh = new BABYLON.BaseSubMesh();
  29513. var scene = this.getScene();
  29514. var checkReady = function () {
  29515. if (!_this._scene || !_this._scene.getEngine()) {
  29516. return;
  29517. }
  29518. if (subMesh._materialDefines) {
  29519. subMesh._materialDefines._renderId = -1;
  29520. }
  29521. var clipPlaneState = scene.clipPlane;
  29522. if (localOptions.clipPlane) {
  29523. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  29524. }
  29525. if (_this.storeEffectOnSubMeshes) {
  29526. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  29527. if (onCompiled) {
  29528. onCompiled(_this);
  29529. }
  29530. }
  29531. else {
  29532. setTimeout(checkReady, 16);
  29533. }
  29534. }
  29535. else {
  29536. if (_this.isReady(mesh)) {
  29537. if (onCompiled) {
  29538. onCompiled(_this);
  29539. }
  29540. }
  29541. else {
  29542. setTimeout(checkReady, 16);
  29543. }
  29544. }
  29545. if (options && options.clipPlane) {
  29546. scene.clipPlane = clipPlaneState;
  29547. }
  29548. };
  29549. checkReady();
  29550. };
  29551. Material.prototype.markAsDirty = function (flag) {
  29552. if (flag & Material.TextureDirtyFlag) {
  29553. this._markAllSubMeshesAsTexturesDirty();
  29554. }
  29555. if (flag & Material.LightDirtyFlag) {
  29556. this._markAllSubMeshesAsLightsDirty();
  29557. }
  29558. if (flag & Material.FresnelDirtyFlag) {
  29559. this._markAllSubMeshesAsFresnelDirty();
  29560. }
  29561. if (flag & Material.AttributesDirtyFlag) {
  29562. this._markAllSubMeshesAsAttributesDirty();
  29563. }
  29564. if (flag & Material.MiscDirtyFlag) {
  29565. this._markAllSubMeshesAsMiscDirty();
  29566. }
  29567. this.getScene().resetCachedMaterial();
  29568. };
  29569. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  29570. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  29571. var mesh = _a[_i];
  29572. if (!mesh.subMeshes) {
  29573. continue;
  29574. }
  29575. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  29576. var subMesh = _c[_b];
  29577. if (subMesh.getMaterial() !== this) {
  29578. continue;
  29579. }
  29580. if (!subMesh._materialDefines) {
  29581. continue;
  29582. }
  29583. func(subMesh._materialDefines);
  29584. }
  29585. }
  29586. };
  29587. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  29588. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  29589. };
  29590. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  29591. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  29592. };
  29593. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  29594. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  29595. };
  29596. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  29597. this._markAllSubMeshesAsDirty(function (defines) {
  29598. defines.markAsFresnelDirty();
  29599. defines.markAsMiscDirty();
  29600. });
  29601. };
  29602. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  29603. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  29604. };
  29605. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  29606. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  29607. };
  29608. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  29609. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  29610. };
  29611. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  29612. this._markAllSubMeshesAsDirty(function (defines) {
  29613. defines.markAsTexturesDirty();
  29614. defines.markAsMiscDirty();
  29615. });
  29616. };
  29617. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  29618. // Animations
  29619. this.getScene().stopAnimation(this);
  29620. // Remove from scene
  29621. var index = this._scene.materials.indexOf(this);
  29622. if (index >= 0) {
  29623. this._scene.materials.splice(index, 1);
  29624. }
  29625. // Remove from meshes
  29626. for (index = 0; index < this._scene.meshes.length; index++) {
  29627. var mesh = this._scene.meshes[index];
  29628. if (mesh.material === this) {
  29629. mesh.material = null;
  29630. if (mesh.geometry) {
  29631. var geometry = (mesh.geometry);
  29632. if (this.storeEffectOnSubMeshes) {
  29633. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  29634. var subMesh = _a[_i];
  29635. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  29636. if (forceDisposeEffect && subMesh._materialEffect) {
  29637. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  29638. }
  29639. }
  29640. }
  29641. else {
  29642. geometry._releaseVertexArrayObject(this._effect);
  29643. }
  29644. }
  29645. }
  29646. }
  29647. this._uniformBuffer.dispose();
  29648. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  29649. if (forceDisposeEffect && this._effect) {
  29650. if (!this.storeEffectOnSubMeshes) {
  29651. this._scene.getEngine()._releaseEffect(this._effect);
  29652. }
  29653. this._effect = null;
  29654. }
  29655. // Callback
  29656. this.onDisposeObservable.notifyObservers(this);
  29657. this.onDisposeObservable.clear();
  29658. this.onBindObservable.clear();
  29659. this.onUnBindObservable.clear();
  29660. };
  29661. Material.prototype.serialize = function () {
  29662. return BABYLON.SerializationHelper.Serialize(this);
  29663. };
  29664. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  29665. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  29666. multiMaterial.id = parsedMultiMaterial.id;
  29667. if (BABYLON.Tags) {
  29668. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  29669. }
  29670. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  29671. var subMatId = parsedMultiMaterial.materials[matIndex];
  29672. if (subMatId) {
  29673. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  29674. }
  29675. else {
  29676. multiMaterial.subMaterials.push(null);
  29677. }
  29678. }
  29679. return multiMaterial;
  29680. };
  29681. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  29682. if (!parsedMaterial.customType) {
  29683. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  29684. }
  29685. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  29686. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  29687. if (!BABYLON.LegacyPBRMaterial) {
  29688. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  29689. return;
  29690. }
  29691. }
  29692. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  29693. return materialType.Parse(parsedMaterial, scene, rootUrl);
  29694. ;
  29695. };
  29696. // Triangle views
  29697. Material._TriangleFillMode = 0;
  29698. Material._WireFrameFillMode = 1;
  29699. Material._PointFillMode = 2;
  29700. // Draw modes
  29701. Material._PointListDrawMode = 3;
  29702. Material._LineListDrawMode = 4;
  29703. Material._LineLoopDrawMode = 5;
  29704. Material._LineStripDrawMode = 6;
  29705. Material._TriangleStripDrawMode = 7;
  29706. Material._TriangleFanDrawMode = 8;
  29707. Material._ClockWiseSideOrientation = 0;
  29708. Material._CounterClockWiseSideOrientation = 1;
  29709. Material._TextureDirtyFlag = 1;
  29710. Material._LightDirtyFlag = 2;
  29711. Material._FresnelDirtyFlag = 4;
  29712. Material._AttributesDirtyFlag = 8;
  29713. Material._MiscDirtyFlag = 16;
  29714. __decorate([
  29715. BABYLON.serialize()
  29716. ], Material.prototype, "id", void 0);
  29717. __decorate([
  29718. BABYLON.serialize()
  29719. ], Material.prototype, "name", void 0);
  29720. __decorate([
  29721. BABYLON.serialize()
  29722. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  29723. __decorate([
  29724. BABYLON.serialize()
  29725. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  29726. __decorate([
  29727. BABYLON.serialize()
  29728. ], Material.prototype, "state", void 0);
  29729. __decorate([
  29730. BABYLON.serialize("alpha")
  29731. ], Material.prototype, "_alpha", void 0);
  29732. __decorate([
  29733. BABYLON.serialize("backFaceCulling")
  29734. ], Material.prototype, "_backFaceCulling", void 0);
  29735. __decorate([
  29736. BABYLON.serialize()
  29737. ], Material.prototype, "sideOrientation", void 0);
  29738. __decorate([
  29739. BABYLON.serialize("alphaMode")
  29740. ], Material.prototype, "_alphaMode", void 0);
  29741. __decorate([
  29742. BABYLON.serialize()
  29743. ], Material.prototype, "_needDepthPrePass", void 0);
  29744. __decorate([
  29745. BABYLON.serialize()
  29746. ], Material.prototype, "disableDepthWrite", void 0);
  29747. __decorate([
  29748. BABYLON.serialize()
  29749. ], Material.prototype, "forceDepthWrite", void 0);
  29750. __decorate([
  29751. BABYLON.serialize()
  29752. ], Material.prototype, "separateCullingPass", void 0);
  29753. __decorate([
  29754. BABYLON.serialize("fogEnabled")
  29755. ], Material.prototype, "_fogEnabled", void 0);
  29756. __decorate([
  29757. BABYLON.serialize()
  29758. ], Material.prototype, "pointSize", void 0);
  29759. __decorate([
  29760. BABYLON.serialize()
  29761. ], Material.prototype, "zOffset", void 0);
  29762. __decorate([
  29763. BABYLON.serialize()
  29764. ], Material.prototype, "wireframe", null);
  29765. __decorate([
  29766. BABYLON.serialize()
  29767. ], Material.prototype, "pointsCloud", null);
  29768. __decorate([
  29769. BABYLON.serialize()
  29770. ], Material.prototype, "fillMode", null);
  29771. return Material;
  29772. }());
  29773. BABYLON.Material = Material;
  29774. })(BABYLON || (BABYLON = {}));
  29775. //# sourceMappingURL=babylon.material.js.map
  29776. var BABYLON;
  29777. (function (BABYLON) {
  29778. var UniformBuffer = /** @class */ (function () {
  29779. /**
  29780. * Uniform buffer objects.
  29781. *
  29782. * Handles blocks of uniform on the GPU.
  29783. *
  29784. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  29785. *
  29786. * For more information, please refer to :
  29787. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  29788. */
  29789. function UniformBuffer(engine, data, dynamic) {
  29790. this._engine = engine;
  29791. this._noUBO = !engine.supportsUniformBuffers;
  29792. this._dynamic = dynamic;
  29793. this._data = data || [];
  29794. this._uniformLocations = {};
  29795. this._uniformSizes = {};
  29796. this._uniformLocationPointer = 0;
  29797. this._needSync = false;
  29798. if (this._noUBO) {
  29799. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  29800. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  29801. this.updateFloat = this._updateFloatForEffect;
  29802. this.updateFloat2 = this._updateFloat2ForEffect;
  29803. this.updateFloat3 = this._updateFloat3ForEffect;
  29804. this.updateFloat4 = this._updateFloat4ForEffect;
  29805. this.updateMatrix = this._updateMatrixForEffect;
  29806. this.updateVector3 = this._updateVector3ForEffect;
  29807. this.updateVector4 = this._updateVector4ForEffect;
  29808. this.updateColor3 = this._updateColor3ForEffect;
  29809. this.updateColor4 = this._updateColor4ForEffect;
  29810. }
  29811. else {
  29812. this._engine._uniformBuffers.push(this);
  29813. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  29814. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  29815. this.updateFloat = this._updateFloatForUniform;
  29816. this.updateFloat2 = this._updateFloat2ForUniform;
  29817. this.updateFloat3 = this._updateFloat3ForUniform;
  29818. this.updateFloat4 = this._updateFloat4ForUniform;
  29819. this.updateMatrix = this._updateMatrixForUniform;
  29820. this.updateVector3 = this._updateVector3ForUniform;
  29821. this.updateVector4 = this._updateVector4ForUniform;
  29822. this.updateColor3 = this._updateColor3ForUniform;
  29823. this.updateColor4 = this._updateColor4ForUniform;
  29824. }
  29825. }
  29826. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  29827. // Properties
  29828. /**
  29829. * Indicates if the buffer is using the WebGL2 UBO implementation,
  29830. * or just falling back on setUniformXXX calls.
  29831. */
  29832. get: function () {
  29833. return !this._noUBO;
  29834. },
  29835. enumerable: true,
  29836. configurable: true
  29837. });
  29838. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  29839. /**
  29840. * Indicates if the WebGL underlying uniform buffer is in sync
  29841. * with the javascript cache data.
  29842. */
  29843. get: function () {
  29844. return !this._needSync;
  29845. },
  29846. enumerable: true,
  29847. configurable: true
  29848. });
  29849. /**
  29850. * Indicates if the WebGL underlying uniform buffer is dynamic.
  29851. * Also, a dynamic UniformBuffer will disable cache verification and always
  29852. * update the underlying WebGL uniform buffer to the GPU.
  29853. */
  29854. UniformBuffer.prototype.isDynamic = function () {
  29855. return this._dynamic !== undefined;
  29856. };
  29857. /**
  29858. * The data cache on JS side.
  29859. */
  29860. UniformBuffer.prototype.getData = function () {
  29861. return this._bufferData;
  29862. };
  29863. /**
  29864. * The underlying WebGL Uniform buffer.
  29865. */
  29866. UniformBuffer.prototype.getBuffer = function () {
  29867. return this._buffer;
  29868. };
  29869. /**
  29870. * std140 layout specifies how to align data within an UBO structure.
  29871. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  29872. * for specs.
  29873. */
  29874. UniformBuffer.prototype._fillAlignment = function (size) {
  29875. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  29876. // and 4x4 matrices
  29877. // TODO : change if other types are used
  29878. var alignment;
  29879. if (size <= 2) {
  29880. alignment = size;
  29881. }
  29882. else {
  29883. alignment = 4;
  29884. }
  29885. if ((this._uniformLocationPointer % alignment) !== 0) {
  29886. var oldPointer = this._uniformLocationPointer;
  29887. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  29888. var diff = this._uniformLocationPointer - oldPointer;
  29889. for (var i = 0; i < diff; i++) {
  29890. this._data.push(0);
  29891. }
  29892. }
  29893. };
  29894. /**
  29895. * Adds an uniform in the buffer.
  29896. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  29897. * for the layout to be correct !
  29898. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29899. * @param {number|number[]} size Data size, or data directly.
  29900. */
  29901. UniformBuffer.prototype.addUniform = function (name, size) {
  29902. if (this._noUBO) {
  29903. return;
  29904. }
  29905. if (this._uniformLocations[name] !== undefined) {
  29906. // Already existing uniform
  29907. return;
  29908. }
  29909. // This function must be called in the order of the shader layout !
  29910. // size can be the size of the uniform, or data directly
  29911. var data;
  29912. if (size instanceof Array) {
  29913. data = size;
  29914. size = data.length;
  29915. }
  29916. else {
  29917. size = size;
  29918. data = [];
  29919. // Fill with zeros
  29920. for (var i = 0; i < size; i++) {
  29921. data.push(0);
  29922. }
  29923. }
  29924. this._fillAlignment(size);
  29925. this._uniformSizes[name] = size;
  29926. this._uniformLocations[name] = this._uniformLocationPointer;
  29927. this._uniformLocationPointer += size;
  29928. for (var i = 0; i < size; i++) {
  29929. this._data.push(data[i]);
  29930. }
  29931. this._needSync = true;
  29932. };
  29933. /**
  29934. * Wrapper for addUniform.
  29935. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29936. * @param {Matrix} mat A 4x4 matrix.
  29937. */
  29938. UniformBuffer.prototype.addMatrix = function (name, mat) {
  29939. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  29940. };
  29941. /**
  29942. * Wrapper for addUniform.
  29943. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29944. * @param {number} x
  29945. * @param {number} y
  29946. */
  29947. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  29948. var temp = [x, y];
  29949. this.addUniform(name, temp);
  29950. };
  29951. /**
  29952. * Wrapper for addUniform.
  29953. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29954. * @param {number} x
  29955. * @param {number} y
  29956. * @param {number} z
  29957. */
  29958. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  29959. var temp = [x, y, z];
  29960. this.addUniform(name, temp);
  29961. };
  29962. /**
  29963. * Wrapper for addUniform.
  29964. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29965. * @param {Color3} color
  29966. */
  29967. UniformBuffer.prototype.addColor3 = function (name, color) {
  29968. var temp = new Array();
  29969. color.toArray(temp);
  29970. this.addUniform(name, temp);
  29971. };
  29972. /**
  29973. * Wrapper for addUniform.
  29974. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29975. * @param {Color3} color
  29976. * @param {number} alpha
  29977. */
  29978. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  29979. var temp = new Array();
  29980. color.toArray(temp);
  29981. temp.push(alpha);
  29982. this.addUniform(name, temp);
  29983. };
  29984. /**
  29985. * Wrapper for addUniform.
  29986. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29987. * @param {Vector3} vector
  29988. */
  29989. UniformBuffer.prototype.addVector3 = function (name, vector) {
  29990. var temp = new Array();
  29991. vector.toArray(temp);
  29992. this.addUniform(name, temp);
  29993. };
  29994. /**
  29995. * Wrapper for addUniform.
  29996. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29997. */
  29998. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  29999. this.addUniform(name, 12);
  30000. };
  30001. /**
  30002. * Wrapper for addUniform.
  30003. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  30004. */
  30005. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  30006. this.addUniform(name, 8);
  30007. };
  30008. /**
  30009. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  30010. */
  30011. UniformBuffer.prototype.create = function () {
  30012. if (this._noUBO) {
  30013. return;
  30014. }
  30015. if (this._buffer) {
  30016. return; // nothing to do
  30017. }
  30018. // See spec, alignment must be filled as a vec4
  30019. this._fillAlignment(4);
  30020. this._bufferData = new Float32Array(this._data);
  30021. this._rebuild();
  30022. this._needSync = true;
  30023. };
  30024. UniformBuffer.prototype._rebuild = function () {
  30025. if (this._noUBO) {
  30026. return;
  30027. }
  30028. if (this._dynamic) {
  30029. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  30030. }
  30031. else {
  30032. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  30033. }
  30034. };
  30035. /**
  30036. * Updates the WebGL Uniform Buffer on the GPU.
  30037. * If the `dynamic` flag is set to true, no cache comparison is done.
  30038. * Otherwise, the buffer will be updated only if the cache differs.
  30039. */
  30040. UniformBuffer.prototype.update = function () {
  30041. if (!this._buffer) {
  30042. this.create();
  30043. return;
  30044. }
  30045. if (!this._dynamic && !this._needSync) {
  30046. return;
  30047. }
  30048. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  30049. this._needSync = false;
  30050. };
  30051. /**
  30052. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  30053. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  30054. * @param {number[]|Float32Array} data Flattened data
  30055. * @param {number} size Size of the data.
  30056. */
  30057. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  30058. var location = this._uniformLocations[uniformName];
  30059. if (location === undefined) {
  30060. if (this._buffer) {
  30061. // Cannot add an uniform if the buffer is already created
  30062. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  30063. return;
  30064. }
  30065. this.addUniform(uniformName, size);
  30066. location = this._uniformLocations[uniformName];
  30067. }
  30068. if (!this._buffer) {
  30069. this.create();
  30070. }
  30071. if (!this._dynamic) {
  30072. // Cache for static uniform buffers
  30073. var changed = false;
  30074. for (var i = 0; i < size; i++) {
  30075. if (this._bufferData[location + i] !== data[i]) {
  30076. changed = true;
  30077. this._bufferData[location + i] = data[i];
  30078. }
  30079. }
  30080. this._needSync = this._needSync || changed;
  30081. }
  30082. else {
  30083. // No cache for dynamic
  30084. for (var i = 0; i < size; i++) {
  30085. this._bufferData[location + i] = data[i];
  30086. }
  30087. }
  30088. };
  30089. // Update methods
  30090. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  30091. // To match std140, matrix must be realigned
  30092. for (var i = 0; i < 3; i++) {
  30093. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  30094. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  30095. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  30096. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  30097. }
  30098. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  30099. };
  30100. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  30101. this._currentEffect.setMatrix3x3(name, matrix);
  30102. };
  30103. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  30104. this._currentEffect.setMatrix2x2(name, matrix);
  30105. };
  30106. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  30107. // To match std140, matrix must be realigned
  30108. for (var i = 0; i < 2; i++) {
  30109. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  30110. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  30111. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  30112. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  30113. }
  30114. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  30115. };
  30116. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  30117. this._currentEffect.setFloat(name, x);
  30118. };
  30119. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  30120. UniformBuffer._tempBuffer[0] = x;
  30121. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  30122. };
  30123. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  30124. if (suffix === void 0) { suffix = ""; }
  30125. this._currentEffect.setFloat2(name + suffix, x, y);
  30126. };
  30127. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  30128. if (suffix === void 0) { suffix = ""; }
  30129. UniformBuffer._tempBuffer[0] = x;
  30130. UniformBuffer._tempBuffer[1] = y;
  30131. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  30132. };
  30133. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  30134. if (suffix === void 0) { suffix = ""; }
  30135. this._currentEffect.setFloat3(name + suffix, x, y, z);
  30136. };
  30137. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  30138. if (suffix === void 0) { suffix = ""; }
  30139. UniformBuffer._tempBuffer[0] = x;
  30140. UniformBuffer._tempBuffer[1] = y;
  30141. UniformBuffer._tempBuffer[2] = z;
  30142. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  30143. };
  30144. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  30145. if (suffix === void 0) { suffix = ""; }
  30146. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  30147. };
  30148. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  30149. if (suffix === void 0) { suffix = ""; }
  30150. UniformBuffer._tempBuffer[0] = x;
  30151. UniformBuffer._tempBuffer[1] = y;
  30152. UniformBuffer._tempBuffer[2] = z;
  30153. UniformBuffer._tempBuffer[3] = w;
  30154. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  30155. };
  30156. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  30157. this._currentEffect.setMatrix(name, mat);
  30158. };
  30159. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  30160. this.updateUniform(name, mat.toArray(), 16);
  30161. };
  30162. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  30163. this._currentEffect.setVector3(name, vector);
  30164. };
  30165. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  30166. vector.toArray(UniformBuffer._tempBuffer);
  30167. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  30168. };
  30169. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  30170. this._currentEffect.setVector4(name, vector);
  30171. };
  30172. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  30173. vector.toArray(UniformBuffer._tempBuffer);
  30174. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  30175. };
  30176. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  30177. if (suffix === void 0) { suffix = ""; }
  30178. this._currentEffect.setColor3(name + suffix, color);
  30179. };
  30180. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  30181. if (suffix === void 0) { suffix = ""; }
  30182. color.toArray(UniformBuffer._tempBuffer);
  30183. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  30184. };
  30185. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  30186. if (suffix === void 0) { suffix = ""; }
  30187. this._currentEffect.setColor4(name + suffix, color, alpha);
  30188. };
  30189. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  30190. if (suffix === void 0) { suffix = ""; }
  30191. color.toArray(UniformBuffer._tempBuffer);
  30192. UniformBuffer._tempBuffer[3] = alpha;
  30193. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  30194. };
  30195. /**
  30196. * Sets a sampler uniform on the effect.
  30197. * @param {string} name Name of the sampler.
  30198. * @param {Texture} texture
  30199. */
  30200. UniformBuffer.prototype.setTexture = function (name, texture) {
  30201. this._currentEffect.setTexture(name, texture);
  30202. };
  30203. /**
  30204. * Directly updates the value of the uniform in the cache AND on the GPU.
  30205. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  30206. * @param {number[]|Float32Array} data Flattened data
  30207. */
  30208. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  30209. this.updateUniform(uniformName, data, data.length);
  30210. this.update();
  30211. };
  30212. /**
  30213. * Binds this uniform buffer to an effect.
  30214. * @param {Effect} effect
  30215. * @param {string} name Name of the uniform block in the shader.
  30216. */
  30217. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  30218. this._currentEffect = effect;
  30219. if (this._noUBO || !this._buffer) {
  30220. return;
  30221. }
  30222. effect.bindUniformBuffer(this._buffer, name);
  30223. };
  30224. /**
  30225. * Disposes the uniform buffer.
  30226. */
  30227. UniformBuffer.prototype.dispose = function () {
  30228. if (this._noUBO) {
  30229. return;
  30230. }
  30231. var index = this._engine._uniformBuffers.indexOf(this);
  30232. if (index !== -1) {
  30233. this._engine._uniformBuffers.splice(index, 1);
  30234. }
  30235. if (!this._buffer) {
  30236. return;
  30237. }
  30238. if (this._engine._releaseBuffer(this._buffer)) {
  30239. this._buffer = null;
  30240. }
  30241. };
  30242. // Pool for avoiding memory leaks
  30243. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  30244. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  30245. return UniformBuffer;
  30246. }());
  30247. BABYLON.UniformBuffer = UniformBuffer;
  30248. })(BABYLON || (BABYLON = {}));
  30249. //# sourceMappingURL=babylon.uniformBuffer.js.map
  30250. var BABYLON;
  30251. (function (BABYLON) {
  30252. var VertexData = /** @class */ (function () {
  30253. function VertexData() {
  30254. }
  30255. VertexData.prototype.set = function (data, kind) {
  30256. switch (kind) {
  30257. case BABYLON.VertexBuffer.PositionKind:
  30258. this.positions = data;
  30259. break;
  30260. case BABYLON.VertexBuffer.NormalKind:
  30261. this.normals = data;
  30262. break;
  30263. case BABYLON.VertexBuffer.TangentKind:
  30264. this.tangents = data;
  30265. break;
  30266. case BABYLON.VertexBuffer.UVKind:
  30267. this.uvs = data;
  30268. break;
  30269. case BABYLON.VertexBuffer.UV2Kind:
  30270. this.uvs2 = data;
  30271. break;
  30272. case BABYLON.VertexBuffer.UV3Kind:
  30273. this.uvs3 = data;
  30274. break;
  30275. case BABYLON.VertexBuffer.UV4Kind:
  30276. this.uvs4 = data;
  30277. break;
  30278. case BABYLON.VertexBuffer.UV5Kind:
  30279. this.uvs5 = data;
  30280. break;
  30281. case BABYLON.VertexBuffer.UV6Kind:
  30282. this.uvs6 = data;
  30283. break;
  30284. case BABYLON.VertexBuffer.ColorKind:
  30285. this.colors = data;
  30286. break;
  30287. case BABYLON.VertexBuffer.MatricesIndicesKind:
  30288. this.matricesIndices = data;
  30289. break;
  30290. case BABYLON.VertexBuffer.MatricesWeightsKind:
  30291. this.matricesWeights = data;
  30292. break;
  30293. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  30294. this.matricesIndicesExtra = data;
  30295. break;
  30296. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  30297. this.matricesWeightsExtra = data;
  30298. break;
  30299. }
  30300. };
  30301. /**
  30302. * Associates the vertexData to the passed Mesh.
  30303. * Sets it as updatable or not (default `false`).
  30304. * Returns the VertexData.
  30305. */
  30306. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  30307. this._applyTo(mesh, updatable);
  30308. return this;
  30309. };
  30310. /**
  30311. * Associates the vertexData to the passed Geometry.
  30312. * Sets it as updatable or not (default `false`).
  30313. * Returns the VertexData.
  30314. */
  30315. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  30316. this._applyTo(geometry, updatable);
  30317. return this;
  30318. };
  30319. /**
  30320. * Updates the associated mesh.
  30321. * Returns the VertexData.
  30322. */
  30323. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  30324. this._update(mesh);
  30325. return this;
  30326. };
  30327. /**
  30328. * Updates the associated geometry.
  30329. * Returns the VertexData.
  30330. */
  30331. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  30332. this._update(geometry);
  30333. return this;
  30334. };
  30335. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  30336. if (updatable === void 0) { updatable = false; }
  30337. if (this.positions) {
  30338. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  30339. }
  30340. if (this.normals) {
  30341. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  30342. }
  30343. if (this.tangents) {
  30344. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  30345. }
  30346. if (this.uvs) {
  30347. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  30348. }
  30349. if (this.uvs2) {
  30350. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  30351. }
  30352. if (this.uvs3) {
  30353. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  30354. }
  30355. if (this.uvs4) {
  30356. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  30357. }
  30358. if (this.uvs5) {
  30359. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  30360. }
  30361. if (this.uvs6) {
  30362. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  30363. }
  30364. if (this.colors) {
  30365. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  30366. }
  30367. if (this.matricesIndices) {
  30368. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  30369. }
  30370. if (this.matricesWeights) {
  30371. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  30372. }
  30373. if (this.matricesIndicesExtra) {
  30374. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  30375. }
  30376. if (this.matricesWeightsExtra) {
  30377. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  30378. }
  30379. if (this.indices) {
  30380. meshOrGeometry.setIndices(this.indices, null, updatable);
  30381. }
  30382. return this;
  30383. };
  30384. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  30385. if (this.positions) {
  30386. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  30387. }
  30388. if (this.normals) {
  30389. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  30390. }
  30391. if (this.tangents) {
  30392. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  30393. }
  30394. if (this.uvs) {
  30395. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  30396. }
  30397. if (this.uvs2) {
  30398. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  30399. }
  30400. if (this.uvs3) {
  30401. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  30402. }
  30403. if (this.uvs4) {
  30404. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  30405. }
  30406. if (this.uvs5) {
  30407. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  30408. }
  30409. if (this.uvs6) {
  30410. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  30411. }
  30412. if (this.colors) {
  30413. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  30414. }
  30415. if (this.matricesIndices) {
  30416. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  30417. }
  30418. if (this.matricesWeights) {
  30419. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  30420. }
  30421. if (this.matricesIndicesExtra) {
  30422. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  30423. }
  30424. if (this.matricesWeightsExtra) {
  30425. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  30426. }
  30427. if (this.indices) {
  30428. meshOrGeometry.setIndices(this.indices, null);
  30429. }
  30430. return this;
  30431. };
  30432. /**
  30433. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  30434. * Returns the VertexData.
  30435. */
  30436. VertexData.prototype.transform = function (matrix) {
  30437. var transformed = BABYLON.Vector3.Zero();
  30438. var index;
  30439. if (this.positions) {
  30440. var position = BABYLON.Vector3.Zero();
  30441. for (index = 0; index < this.positions.length; index += 3) {
  30442. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  30443. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  30444. this.positions[index] = transformed.x;
  30445. this.positions[index + 1] = transformed.y;
  30446. this.positions[index + 2] = transformed.z;
  30447. }
  30448. }
  30449. if (this.normals) {
  30450. var normal = BABYLON.Vector3.Zero();
  30451. for (index = 0; index < this.normals.length; index += 3) {
  30452. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  30453. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  30454. this.normals[index] = transformed.x;
  30455. this.normals[index + 1] = transformed.y;
  30456. this.normals[index + 2] = transformed.z;
  30457. }
  30458. }
  30459. if (this.tangents) {
  30460. var tangent = BABYLON.Vector4.Zero();
  30461. var tangentTransformed = BABYLON.Vector4.Zero();
  30462. for (index = 0; index < this.tangents.length; index += 4) {
  30463. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  30464. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  30465. this.tangents[index] = tangentTransformed.x;
  30466. this.tangents[index + 1] = tangentTransformed.y;
  30467. this.tangents[index + 2] = tangentTransformed.z;
  30468. this.tangents[index + 3] = tangentTransformed.w;
  30469. }
  30470. }
  30471. return this;
  30472. };
  30473. /**
  30474. * Merges the passed VertexData into the current one.
  30475. * Returns the modified VertexData.
  30476. */
  30477. VertexData.prototype.merge = function (other, options) {
  30478. options = options || {};
  30479. if (other.indices) {
  30480. if (!this.indices) {
  30481. this.indices = [];
  30482. }
  30483. var offset = this.positions ? this.positions.length / 3 : 0;
  30484. for (var index = 0; index < other.indices.length; index++) {
  30485. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  30486. this.indices.push(other.indices[index] + offset);
  30487. }
  30488. }
  30489. this.positions = this._mergeElement(this.positions, other.positions);
  30490. if (!this.positions) {
  30491. return this;
  30492. }
  30493. var count = this.positions.length / 3;
  30494. this.normals = this._mergeElement(this.normals, other.normals, count * 3);
  30495. this.tangents = this._mergeElement(this.tangents, other.tangents, count * (options.tangentLength || 4));
  30496. this.uvs = this._mergeElement(this.uvs, other.uvs, count * 2);
  30497. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2, count * 2);
  30498. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3, count * 2);
  30499. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4, count * 2);
  30500. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5, count * 2);
  30501. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6, count * 2);
  30502. this.colors = this._mergeElement(this.colors, other.colors, count * 4, 1);
  30503. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices, count * 4);
  30504. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights, count * 4);
  30505. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra, count * 4);
  30506. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra, count * 4);
  30507. return this;
  30508. };
  30509. VertexData.prototype._mergeElement = function (source, other, length, defaultValue) {
  30510. if (length === void 0) { length = 0; }
  30511. if (defaultValue === void 0) { defaultValue = 0; }
  30512. if (!other && !source) {
  30513. return null;
  30514. }
  30515. if (!other) {
  30516. var padding = new Float32Array(source.length);
  30517. padding.fill(defaultValue);
  30518. return this._mergeElement(source, padding, length);
  30519. }
  30520. if (!source) {
  30521. if (length === 0 || length === other.length) {
  30522. return other;
  30523. }
  30524. var padding = new Float32Array(length - other.length);
  30525. padding.fill(defaultValue);
  30526. return this._mergeElement(padding, other, length);
  30527. }
  30528. var len = other.length + source.length;
  30529. var isSrcTypedArray = source instanceof Float32Array;
  30530. var isOthTypedArray = other instanceof Float32Array;
  30531. // use non-loop method when the source is Float32Array
  30532. if (isSrcTypedArray) {
  30533. var ret32 = new Float32Array(len);
  30534. ret32.set(source);
  30535. ret32.set(other, source.length);
  30536. return ret32;
  30537. // source is number[], when other is also use concat
  30538. }
  30539. else if (!isOthTypedArray) {
  30540. return source.concat(other);
  30541. // source is a number[], but other is a Float32Array, loop required
  30542. }
  30543. else {
  30544. var ret = source.slice(0); // copy source to a separate array
  30545. for (var i = 0, len = other.length; i < len; i++) {
  30546. ret.push(other[i]);
  30547. }
  30548. return ret;
  30549. }
  30550. };
  30551. /**
  30552. * Serializes the VertexData.
  30553. * Returns a serialized object.
  30554. */
  30555. VertexData.prototype.serialize = function () {
  30556. var serializationObject = this.serialize();
  30557. if (this.positions) {
  30558. serializationObject.positions = this.positions;
  30559. }
  30560. if (this.normals) {
  30561. serializationObject.normals = this.normals;
  30562. }
  30563. if (this.tangents) {
  30564. serializationObject.tangents = this.tangents;
  30565. }
  30566. if (this.uvs) {
  30567. serializationObject.uvs = this.uvs;
  30568. }
  30569. if (this.uvs2) {
  30570. serializationObject.uvs2 = this.uvs2;
  30571. }
  30572. if (this.uvs3) {
  30573. serializationObject.uvs3 = this.uvs3;
  30574. }
  30575. if (this.uvs4) {
  30576. serializationObject.uvs4 = this.uvs4;
  30577. }
  30578. if (this.uvs5) {
  30579. serializationObject.uvs5 = this.uvs5;
  30580. }
  30581. if (this.uvs6) {
  30582. serializationObject.uvs6 = this.uvs6;
  30583. }
  30584. if (this.colors) {
  30585. serializationObject.colors = this.colors;
  30586. }
  30587. if (this.matricesIndices) {
  30588. serializationObject.matricesIndices = this.matricesIndices;
  30589. serializationObject.matricesIndices._isExpanded = true;
  30590. }
  30591. if (this.matricesWeights) {
  30592. serializationObject.matricesWeights = this.matricesWeights;
  30593. }
  30594. if (this.matricesIndicesExtra) {
  30595. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  30596. serializationObject.matricesIndicesExtra._isExpanded = true;
  30597. }
  30598. if (this.matricesWeightsExtra) {
  30599. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  30600. }
  30601. serializationObject.indices = this.indices;
  30602. return serializationObject;
  30603. };
  30604. // Statics
  30605. /**
  30606. * Returns the object VertexData associated to the passed mesh.
  30607. */
  30608. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  30609. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  30610. };
  30611. /**
  30612. * Returns the object VertexData associated to the passed geometry.
  30613. */
  30614. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  30615. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  30616. };
  30617. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  30618. var result = new VertexData();
  30619. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30620. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  30621. }
  30622. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30623. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  30624. }
  30625. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  30626. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  30627. }
  30628. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30629. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  30630. }
  30631. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  30632. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  30633. }
  30634. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  30635. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  30636. }
  30637. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  30638. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  30639. }
  30640. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  30641. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  30642. }
  30643. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  30644. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  30645. }
  30646. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  30647. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  30648. }
  30649. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30650. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  30651. }
  30652. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30653. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  30654. }
  30655. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  30656. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  30657. }
  30658. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  30659. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  30660. }
  30661. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  30662. return result;
  30663. };
  30664. /**
  30665. * Creates the vertexData of the Ribbon.
  30666. */
  30667. VertexData.CreateRibbon = function (options) {
  30668. var pathArray = options.pathArray;
  30669. var closeArray = options.closeArray || false;
  30670. var closePath = options.closePath || false;
  30671. var invertUV = options.invertUV || false;
  30672. var defaultOffset = Math.floor(pathArray[0].length / 2);
  30673. var offset = options.offset || defaultOffset;
  30674. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  30675. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30676. var customUV = options.uvs;
  30677. var customColors = options.colors;
  30678. var positions = [];
  30679. var indices = [];
  30680. var normals = [];
  30681. var uvs = [];
  30682. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  30683. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  30684. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  30685. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  30686. var minlg; // minimal length among all paths from pathArray
  30687. var lg = []; // array of path lengths : nb of vertex per path
  30688. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  30689. var p; // path iterator
  30690. var i; // point iterator
  30691. var j; // point iterator
  30692. // if single path in pathArray
  30693. if (pathArray.length < 2) {
  30694. var ar1 = [];
  30695. var ar2 = [];
  30696. for (i = 0; i < pathArray[0].length - offset; i++) {
  30697. ar1.push(pathArray[0][i]);
  30698. ar2.push(pathArray[0][i + offset]);
  30699. }
  30700. pathArray = [ar1, ar2];
  30701. }
  30702. // positions and horizontal distances (u)
  30703. var idc = 0;
  30704. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  30705. var path;
  30706. var l;
  30707. minlg = pathArray[0].length;
  30708. var vectlg;
  30709. var dist;
  30710. for (p = 0; p < pathArray.length; p++) {
  30711. uTotalDistance[p] = 0;
  30712. us[p] = [0];
  30713. path = pathArray[p];
  30714. l = path.length;
  30715. minlg = (minlg < l) ? minlg : l;
  30716. j = 0;
  30717. while (j < l) {
  30718. positions.push(path[j].x, path[j].y, path[j].z);
  30719. if (j > 0) {
  30720. vectlg = path[j].subtract(path[j - 1]).length();
  30721. dist = vectlg + uTotalDistance[p];
  30722. us[p].push(dist);
  30723. uTotalDistance[p] = dist;
  30724. }
  30725. j++;
  30726. }
  30727. if (closePath) {
  30728. j--;
  30729. positions.push(path[0].x, path[0].y, path[0].z);
  30730. vectlg = path[j].subtract(path[0]).length();
  30731. dist = vectlg + uTotalDistance[p];
  30732. us[p].push(dist);
  30733. uTotalDistance[p] = dist;
  30734. }
  30735. lg[p] = l + closePathCorr;
  30736. idx[p] = idc;
  30737. idc += (l + closePathCorr);
  30738. }
  30739. // vertical distances (v)
  30740. var path1;
  30741. var path2;
  30742. var vertex1 = null;
  30743. var vertex2 = null;
  30744. for (i = 0; i < minlg + closePathCorr; i++) {
  30745. vTotalDistance[i] = 0;
  30746. vs[i] = [0];
  30747. for (p = 0; p < pathArray.length - 1; p++) {
  30748. path1 = pathArray[p];
  30749. path2 = pathArray[p + 1];
  30750. if (i === minlg) {
  30751. vertex1 = path1[0];
  30752. vertex2 = path2[0];
  30753. }
  30754. else {
  30755. vertex1 = path1[i];
  30756. vertex2 = path2[i];
  30757. }
  30758. vectlg = vertex2.subtract(vertex1).length();
  30759. dist = vectlg + vTotalDistance[i];
  30760. vs[i].push(dist);
  30761. vTotalDistance[i] = dist;
  30762. }
  30763. if (closeArray && vertex2 && vertex1) {
  30764. path1 = pathArray[p];
  30765. path2 = pathArray[0];
  30766. if (i === minlg) {
  30767. vertex2 = path2[0];
  30768. }
  30769. vectlg = vertex2.subtract(vertex1).length();
  30770. dist = vectlg + vTotalDistance[i];
  30771. vTotalDistance[i] = dist;
  30772. }
  30773. }
  30774. // uvs
  30775. var u;
  30776. var v;
  30777. if (customUV) {
  30778. for (p = 0; p < customUV.length; p++) {
  30779. uvs.push(customUV[p].x, customUV[p].y);
  30780. }
  30781. }
  30782. else {
  30783. for (p = 0; p < pathArray.length; p++) {
  30784. for (i = 0; i < minlg + closePathCorr; i++) {
  30785. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  30786. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  30787. if (invertUV) {
  30788. uvs.push(v, u);
  30789. }
  30790. else {
  30791. uvs.push(u, v);
  30792. }
  30793. }
  30794. }
  30795. }
  30796. // indices
  30797. p = 0; // path index
  30798. var pi = 0; // positions array index
  30799. var l1 = lg[p] - 1; // path1 length
  30800. var l2 = lg[p + 1] - 1; // path2 length
  30801. var min = (l1 < l2) ? l1 : l2; // current path stop index
  30802. var shft = idx[1] - idx[0]; // shift
  30803. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  30804. while (pi <= min && p < path1nb) {
  30805. // 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
  30806. indices.push(pi, pi + shft, pi + 1);
  30807. indices.push(pi + shft + 1, pi + 1, pi + shft);
  30808. pi += 1;
  30809. if (pi === min) {
  30810. p++;
  30811. if (p === lg.length - 1) {
  30812. shft = idx[0] - idx[p];
  30813. l1 = lg[p] - 1;
  30814. l2 = lg[0] - 1;
  30815. }
  30816. else {
  30817. shft = idx[p + 1] - idx[p];
  30818. l1 = lg[p] - 1;
  30819. l2 = lg[p + 1] - 1;
  30820. }
  30821. pi = idx[p];
  30822. min = (l1 < l2) ? l1 + pi : l2 + pi;
  30823. }
  30824. }
  30825. // normals
  30826. VertexData.ComputeNormals(positions, indices, normals);
  30827. if (closePath) {
  30828. var indexFirst = 0;
  30829. var indexLast = 0;
  30830. for (p = 0; p < pathArray.length; p++) {
  30831. indexFirst = idx[p] * 3;
  30832. if (p + 1 < pathArray.length) {
  30833. indexLast = (idx[p + 1] - 1) * 3;
  30834. }
  30835. else {
  30836. indexLast = normals.length - 3;
  30837. }
  30838. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  30839. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  30840. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  30841. normals[indexLast] = normals[indexFirst];
  30842. normals[indexLast + 1] = normals[indexFirst + 1];
  30843. normals[indexLast + 2] = normals[indexFirst + 2];
  30844. }
  30845. }
  30846. // sides
  30847. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30848. // Colors
  30849. var colors = null;
  30850. if (customColors) {
  30851. colors = new Float32Array(customColors.length * 4);
  30852. for (var c = 0; c < customColors.length; c++) {
  30853. colors[c * 4] = customColors[c].r;
  30854. colors[c * 4 + 1] = customColors[c].g;
  30855. colors[c * 4 + 2] = customColors[c].b;
  30856. colors[c * 4 + 3] = customColors[c].a;
  30857. }
  30858. }
  30859. // Result
  30860. var vertexData = new VertexData();
  30861. var positions32 = new Float32Array(positions);
  30862. var normals32 = new Float32Array(normals);
  30863. var uvs32 = new Float32Array(uvs);
  30864. vertexData.indices = indices;
  30865. vertexData.positions = positions32;
  30866. vertexData.normals = normals32;
  30867. vertexData.uvs = uvs32;
  30868. if (colors) {
  30869. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  30870. }
  30871. if (closePath) {
  30872. vertexData._idx = idx;
  30873. }
  30874. return vertexData;
  30875. };
  30876. /**
  30877. * Creates the VertexData of the Box.
  30878. */
  30879. VertexData.CreateBox = function (options) {
  30880. var normalsSource = [
  30881. new BABYLON.Vector3(0, 0, 1),
  30882. new BABYLON.Vector3(0, 0, -1),
  30883. new BABYLON.Vector3(1, 0, 0),
  30884. new BABYLON.Vector3(-1, 0, 0),
  30885. new BABYLON.Vector3(0, 1, 0),
  30886. new BABYLON.Vector3(0, -1, 0)
  30887. ];
  30888. var indices = [];
  30889. var positions = [];
  30890. var normals = [];
  30891. var uvs = [];
  30892. var width = options.width || options.size || 1;
  30893. var height = options.height || options.size || 1;
  30894. var depth = options.depth || options.size || 1;
  30895. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30896. var faceUV = options.faceUV || new Array(6);
  30897. var faceColors = options.faceColors;
  30898. var colors = [];
  30899. // default face colors and UV if undefined
  30900. for (var f = 0; f < 6; f++) {
  30901. if (faceUV[f] === undefined) {
  30902. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30903. }
  30904. if (faceColors && faceColors[f] === undefined) {
  30905. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30906. }
  30907. }
  30908. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  30909. // Create each face in turn.
  30910. for (var index = 0; index < normalsSource.length; index++) {
  30911. var normal = normalsSource[index];
  30912. // Get two vectors perpendicular to the face normal and to each other.
  30913. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  30914. var side2 = BABYLON.Vector3.Cross(normal, side1);
  30915. // Six indices (two triangles) per face.
  30916. var verticesLength = positions.length / 3;
  30917. indices.push(verticesLength);
  30918. indices.push(verticesLength + 1);
  30919. indices.push(verticesLength + 2);
  30920. indices.push(verticesLength);
  30921. indices.push(verticesLength + 2);
  30922. indices.push(verticesLength + 3);
  30923. // Four vertices per face.
  30924. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  30925. positions.push(vertex.x, vertex.y, vertex.z);
  30926. normals.push(normal.x, normal.y, normal.z);
  30927. uvs.push(faceUV[index].z, faceUV[index].w);
  30928. if (faceColors) {
  30929. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30930. }
  30931. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  30932. positions.push(vertex.x, vertex.y, vertex.z);
  30933. normals.push(normal.x, normal.y, normal.z);
  30934. uvs.push(faceUV[index].x, faceUV[index].w);
  30935. if (faceColors) {
  30936. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30937. }
  30938. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  30939. positions.push(vertex.x, vertex.y, vertex.z);
  30940. normals.push(normal.x, normal.y, normal.z);
  30941. uvs.push(faceUV[index].x, faceUV[index].y);
  30942. if (faceColors) {
  30943. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30944. }
  30945. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  30946. positions.push(vertex.x, vertex.y, vertex.z);
  30947. normals.push(normal.x, normal.y, normal.z);
  30948. uvs.push(faceUV[index].z, faceUV[index].y);
  30949. if (faceColors) {
  30950. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30951. }
  30952. }
  30953. // sides
  30954. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30955. // Result
  30956. var vertexData = new VertexData();
  30957. vertexData.indices = indices;
  30958. vertexData.positions = positions;
  30959. vertexData.normals = normals;
  30960. vertexData.uvs = uvs;
  30961. if (faceColors) {
  30962. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  30963. vertexData.colors = totalColors;
  30964. }
  30965. return vertexData;
  30966. };
  30967. /**
  30968. * Creates the VertexData of the Sphere.
  30969. */
  30970. VertexData.CreateSphere = function (options) {
  30971. var segments = options.segments || 32;
  30972. var diameterX = options.diameterX || options.diameter || 1;
  30973. var diameterY = options.diameterY || options.diameter || 1;
  30974. var diameterZ = options.diameterZ || options.diameter || 1;
  30975. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30976. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  30977. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30978. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  30979. var totalZRotationSteps = 2 + segments;
  30980. var totalYRotationSteps = 2 * totalZRotationSteps;
  30981. var indices = [];
  30982. var positions = [];
  30983. var normals = [];
  30984. var uvs = [];
  30985. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  30986. var normalizedZ = zRotationStep / totalZRotationSteps;
  30987. var angleZ = normalizedZ * Math.PI * slice;
  30988. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  30989. var normalizedY = yRotationStep / totalYRotationSteps;
  30990. var angleY = normalizedY * Math.PI * 2 * arc;
  30991. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  30992. var rotationY = BABYLON.Matrix.RotationY(angleY);
  30993. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  30994. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  30995. var vertex = complete.multiply(radius);
  30996. var normal = complete.divide(radius).normalize();
  30997. positions.push(vertex.x, vertex.y, vertex.z);
  30998. normals.push(normal.x, normal.y, normal.z);
  30999. uvs.push(normalizedY, normalizedZ);
  31000. }
  31001. if (zRotationStep > 0) {
  31002. var verticesCount = positions.length / 3;
  31003. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  31004. indices.push((firstIndex));
  31005. indices.push((firstIndex + 1));
  31006. indices.push(firstIndex + totalYRotationSteps + 1);
  31007. indices.push((firstIndex + totalYRotationSteps + 1));
  31008. indices.push((firstIndex + 1));
  31009. indices.push((firstIndex + totalYRotationSteps + 2));
  31010. }
  31011. }
  31012. }
  31013. // Sides
  31014. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31015. // Result
  31016. var vertexData = new VertexData();
  31017. vertexData.indices = indices;
  31018. vertexData.positions = positions;
  31019. vertexData.normals = normals;
  31020. vertexData.uvs = uvs;
  31021. return vertexData;
  31022. };
  31023. /**
  31024. * Creates the VertexData of the Cylinder or Cone.
  31025. */
  31026. VertexData.CreateCylinder = function (options) {
  31027. var height = options.height || 2;
  31028. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  31029. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  31030. var tessellation = options.tessellation || 24;
  31031. var subdivisions = options.subdivisions || 1;
  31032. var hasRings = options.hasRings ? true : false;
  31033. var enclose = options.enclose ? true : false;
  31034. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  31035. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31036. var faceUV = options.faceUV || new Array(3);
  31037. var faceColors = options.faceColors;
  31038. // default face colors and UV if undefined
  31039. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  31040. var ringNb = (hasRings) ? subdivisions : 1;
  31041. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  31042. var f;
  31043. for (f = 0; f < surfaceNb; f++) {
  31044. if (faceColors && faceColors[f] === undefined) {
  31045. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31046. }
  31047. }
  31048. for (f = 0; f < surfaceNb; f++) {
  31049. if (faceUV && faceUV[f] === undefined) {
  31050. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31051. }
  31052. }
  31053. var indices = new Array();
  31054. var positions = new Array();
  31055. var normals = new Array();
  31056. var uvs = new Array();
  31057. var colors = new Array();
  31058. var angle_step = Math.PI * 2 * arc / tessellation;
  31059. var angle;
  31060. var h;
  31061. var radius;
  31062. var tan = (diameterBottom - diameterTop) / 2 / height;
  31063. var ringVertex = BABYLON.Vector3.Zero();
  31064. var ringNormal = BABYLON.Vector3.Zero();
  31065. var ringFirstVertex = BABYLON.Vector3.Zero();
  31066. var ringFirstNormal = BABYLON.Vector3.Zero();
  31067. var quadNormal = BABYLON.Vector3.Zero();
  31068. var Y = BABYLON.Axis.Y;
  31069. // positions, normals, uvs
  31070. var i;
  31071. var j;
  31072. var r;
  31073. var ringIdx = 1;
  31074. var s = 1; // surface index
  31075. var cs = 0;
  31076. var v = 0;
  31077. for (i = 0; i <= subdivisions; i++) {
  31078. h = i / subdivisions;
  31079. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  31080. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  31081. for (r = 0; r < ringIdx; r++) {
  31082. if (hasRings) {
  31083. s += r;
  31084. }
  31085. if (enclose) {
  31086. s += 2 * r;
  31087. }
  31088. for (j = 0; j <= tessellation; j++) {
  31089. angle = j * angle_step;
  31090. // position
  31091. ringVertex.x = Math.cos(-angle) * radius;
  31092. ringVertex.y = -height / 2 + h * height;
  31093. ringVertex.z = Math.sin(-angle) * radius;
  31094. // normal
  31095. if (diameterTop === 0 && i === subdivisions) {
  31096. // if no top cap, reuse former normals
  31097. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  31098. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  31099. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  31100. }
  31101. else {
  31102. ringNormal.x = ringVertex.x;
  31103. ringNormal.z = ringVertex.z;
  31104. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  31105. ringNormal.normalize();
  31106. }
  31107. // keep first ring vertex values for enclose
  31108. if (j === 0) {
  31109. ringFirstVertex.copyFrom(ringVertex);
  31110. ringFirstNormal.copyFrom(ringNormal);
  31111. }
  31112. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  31113. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  31114. if (hasRings) {
  31115. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  31116. }
  31117. else {
  31118. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  31119. }
  31120. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  31121. if (faceColors) {
  31122. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  31123. }
  31124. }
  31125. // if enclose, add four vertices and their dedicated normals
  31126. if (arc !== 1 && enclose) {
  31127. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  31128. positions.push(0, ringVertex.y, 0);
  31129. positions.push(0, ringVertex.y, 0);
  31130. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  31131. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  31132. quadNormal.normalize();
  31133. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  31134. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  31135. quadNormal.normalize();
  31136. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  31137. if (hasRings) {
  31138. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  31139. }
  31140. else {
  31141. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  31142. }
  31143. uvs.push(faceUV[s + 1].x, v);
  31144. uvs.push(faceUV[s + 1].z, v);
  31145. if (hasRings) {
  31146. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  31147. }
  31148. else {
  31149. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  31150. }
  31151. uvs.push(faceUV[s + 2].x, v);
  31152. uvs.push(faceUV[s + 2].z, v);
  31153. if (faceColors) {
  31154. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  31155. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  31156. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  31157. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  31158. }
  31159. }
  31160. if (cs !== s) {
  31161. cs = s;
  31162. }
  31163. }
  31164. }
  31165. // indices
  31166. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  31167. var s;
  31168. i = 0;
  31169. for (s = 0; s < subdivisions; s++) {
  31170. var i0 = 0;
  31171. var i1 = 0;
  31172. var i2 = 0;
  31173. var i3 = 0;
  31174. for (j = 0; j < tessellation; j++) {
  31175. i0 = i * (e + 1) + j;
  31176. i1 = (i + 1) * (e + 1) + j;
  31177. i2 = i * (e + 1) + (j + 1);
  31178. i3 = (i + 1) * (e + 1) + (j + 1);
  31179. indices.push(i0, i1, i2);
  31180. indices.push(i3, i2, i1);
  31181. }
  31182. if (arc !== 1 && enclose) {
  31183. indices.push(i0 + 2, i1 + 2, i2 + 2);
  31184. indices.push(i3 + 2, i2 + 2, i1 + 2);
  31185. indices.push(i0 + 4, i1 + 4, i2 + 4);
  31186. indices.push(i3 + 4, i2 + 4, i1 + 4);
  31187. }
  31188. i = (hasRings) ? (i + 2) : (i + 1);
  31189. }
  31190. // Caps
  31191. var createCylinderCap = function (isTop) {
  31192. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  31193. if (radius === 0) {
  31194. return;
  31195. }
  31196. // Cap positions, normals & uvs
  31197. var angle;
  31198. var circleVector;
  31199. var i;
  31200. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  31201. var c = null;
  31202. if (faceColors) {
  31203. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  31204. }
  31205. // cap center
  31206. var vbase = positions.length / 3;
  31207. var offset = isTop ? height / 2 : -height / 2;
  31208. var center = new BABYLON.Vector3(0, offset, 0);
  31209. positions.push(center.x, center.y, center.z);
  31210. normals.push(0, isTop ? 1 : -1, 0);
  31211. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  31212. if (c) {
  31213. colors.push(c.r, c.g, c.b, c.a);
  31214. }
  31215. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  31216. for (i = 0; i <= tessellation; i++) {
  31217. angle = Math.PI * 2 * i * arc / tessellation;
  31218. var cos = Math.cos(-angle);
  31219. var sin = Math.sin(-angle);
  31220. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  31221. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  31222. positions.push(circleVector.x, circleVector.y, circleVector.z);
  31223. normals.push(0, isTop ? 1 : -1, 0);
  31224. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  31225. if (c) {
  31226. colors.push(c.r, c.g, c.b, c.a);
  31227. }
  31228. }
  31229. // Cap indices
  31230. for (i = 0; i < tessellation; i++) {
  31231. if (!isTop) {
  31232. indices.push(vbase);
  31233. indices.push(vbase + (i + 1));
  31234. indices.push(vbase + (i + 2));
  31235. }
  31236. else {
  31237. indices.push(vbase);
  31238. indices.push(vbase + (i + 2));
  31239. indices.push(vbase + (i + 1));
  31240. }
  31241. }
  31242. };
  31243. // add caps to geometry
  31244. createCylinderCap(false);
  31245. createCylinderCap(true);
  31246. // Sides
  31247. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31248. var vertexData = new VertexData();
  31249. vertexData.indices = indices;
  31250. vertexData.positions = positions;
  31251. vertexData.normals = normals;
  31252. vertexData.uvs = uvs;
  31253. if (faceColors) {
  31254. vertexData.colors = colors;
  31255. }
  31256. return vertexData;
  31257. };
  31258. /**
  31259. * Creates the VertexData of the Torus.
  31260. */
  31261. VertexData.CreateTorus = function (options) {
  31262. var indices = [];
  31263. var positions = [];
  31264. var normals = [];
  31265. var uvs = [];
  31266. var diameter = options.diameter || 1;
  31267. var thickness = options.thickness || 0.5;
  31268. var tessellation = options.tessellation || 16;
  31269. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31270. var stride = tessellation + 1;
  31271. for (var i = 0; i <= tessellation; i++) {
  31272. var u = i / tessellation;
  31273. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  31274. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  31275. for (var j = 0; j <= tessellation; j++) {
  31276. var v = 1 - j / tessellation;
  31277. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  31278. var dx = Math.cos(innerAngle);
  31279. var dy = Math.sin(innerAngle);
  31280. // Create a vertex.
  31281. var normal = new BABYLON.Vector3(dx, dy, 0);
  31282. var position = normal.scale(thickness / 2);
  31283. var textureCoordinate = new BABYLON.Vector2(u, v);
  31284. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  31285. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  31286. positions.push(position.x, position.y, position.z);
  31287. normals.push(normal.x, normal.y, normal.z);
  31288. uvs.push(textureCoordinate.x, textureCoordinate.y);
  31289. // And create indices for two triangles.
  31290. var nextI = (i + 1) % stride;
  31291. var nextJ = (j + 1) % stride;
  31292. indices.push(i * stride + j);
  31293. indices.push(i * stride + nextJ);
  31294. indices.push(nextI * stride + j);
  31295. indices.push(i * stride + nextJ);
  31296. indices.push(nextI * stride + nextJ);
  31297. indices.push(nextI * stride + j);
  31298. }
  31299. }
  31300. // Sides
  31301. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31302. // Result
  31303. var vertexData = new VertexData();
  31304. vertexData.indices = indices;
  31305. vertexData.positions = positions;
  31306. vertexData.normals = normals;
  31307. vertexData.uvs = uvs;
  31308. return vertexData;
  31309. };
  31310. /**
  31311. * Creates the VertexData of the LineSystem.
  31312. */
  31313. VertexData.CreateLineSystem = function (options) {
  31314. var indices = [];
  31315. var positions = [];
  31316. var lines = options.lines;
  31317. var colors = options.colors;
  31318. var vertexColors = [];
  31319. var idx = 0;
  31320. for (var l = 0; l < lines.length; l++) {
  31321. var points = lines[l];
  31322. for (var index = 0; index < points.length; index++) {
  31323. positions.push(points[index].x, points[index].y, points[index].z);
  31324. if (colors) {
  31325. var color = colors[l];
  31326. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  31327. }
  31328. if (index > 0) {
  31329. indices.push(idx - 1);
  31330. indices.push(idx);
  31331. }
  31332. idx++;
  31333. }
  31334. }
  31335. var vertexData = new VertexData();
  31336. vertexData.indices = indices;
  31337. vertexData.positions = positions;
  31338. if (colors) {
  31339. vertexData.colors = vertexColors;
  31340. }
  31341. return vertexData;
  31342. };
  31343. /**
  31344. * Create the VertexData of the DashedLines.
  31345. */
  31346. VertexData.CreateDashedLines = function (options) {
  31347. var dashSize = options.dashSize || 3;
  31348. var gapSize = options.gapSize || 1;
  31349. var dashNb = options.dashNb || 200;
  31350. var points = options.points;
  31351. var positions = new Array();
  31352. var indices = new Array();
  31353. var curvect = BABYLON.Vector3.Zero();
  31354. var lg = 0;
  31355. var nb = 0;
  31356. var shft = 0;
  31357. var dashshft = 0;
  31358. var curshft = 0;
  31359. var idx = 0;
  31360. var i = 0;
  31361. for (i = 0; i < points.length - 1; i++) {
  31362. points[i + 1].subtractToRef(points[i], curvect);
  31363. lg += curvect.length();
  31364. }
  31365. shft = lg / dashNb;
  31366. dashshft = dashSize * shft / (dashSize + gapSize);
  31367. for (i = 0; i < points.length - 1; i++) {
  31368. points[i + 1].subtractToRef(points[i], curvect);
  31369. nb = Math.floor(curvect.length() / shft);
  31370. curvect.normalize();
  31371. for (var j = 0; j < nb; j++) {
  31372. curshft = shft * j;
  31373. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  31374. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  31375. indices.push(idx, idx + 1);
  31376. idx += 2;
  31377. }
  31378. }
  31379. // Result
  31380. var vertexData = new VertexData();
  31381. vertexData.positions = positions;
  31382. vertexData.indices = indices;
  31383. return vertexData;
  31384. };
  31385. /**
  31386. * Creates the VertexData of the Ground.
  31387. */
  31388. VertexData.CreateGround = function (options) {
  31389. var indices = [];
  31390. var positions = [];
  31391. var normals = [];
  31392. var uvs = [];
  31393. var row, col;
  31394. var width = options.width || 1;
  31395. var height = options.height || 1;
  31396. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  31397. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  31398. for (row = 0; row <= subdivisionsY; row++) {
  31399. for (col = 0; col <= subdivisionsX; col++) {
  31400. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  31401. var normal = new BABYLON.Vector3(0, 1.0, 0);
  31402. positions.push(position.x, position.y, position.z);
  31403. normals.push(normal.x, normal.y, normal.z);
  31404. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  31405. }
  31406. }
  31407. for (row = 0; row < subdivisionsY; row++) {
  31408. for (col = 0; col < subdivisionsX; col++) {
  31409. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  31410. indices.push(col + 1 + row * (subdivisionsX + 1));
  31411. indices.push(col + row * (subdivisionsX + 1));
  31412. indices.push(col + (row + 1) * (subdivisionsX + 1));
  31413. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  31414. indices.push(col + row * (subdivisionsX + 1));
  31415. }
  31416. }
  31417. // Result
  31418. var vertexData = new VertexData();
  31419. vertexData.indices = indices;
  31420. vertexData.positions = positions;
  31421. vertexData.normals = normals;
  31422. vertexData.uvs = uvs;
  31423. return vertexData;
  31424. };
  31425. /**
  31426. * Creates the VertexData of the TiledGround.
  31427. */
  31428. VertexData.CreateTiledGround = function (options) {
  31429. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  31430. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  31431. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  31432. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  31433. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  31434. var precision = options.precision || { w: 1, h: 1 };
  31435. var indices = new Array();
  31436. var positions = new Array();
  31437. var normals = new Array();
  31438. var uvs = new Array();
  31439. var row, col, tileRow, tileCol;
  31440. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  31441. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  31442. precision.w = (precision.w < 1) ? 1 : precision.w;
  31443. precision.h = (precision.h < 1) ? 1 : precision.h;
  31444. var tileSize = {
  31445. 'w': (xmax - xmin) / subdivisions.w,
  31446. 'h': (zmax - zmin) / subdivisions.h
  31447. };
  31448. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  31449. // Indices
  31450. var base = positions.length / 3;
  31451. var rowLength = precision.w + 1;
  31452. for (row = 0; row < precision.h; row++) {
  31453. for (col = 0; col < precision.w; col++) {
  31454. var square = [
  31455. base + col + row * rowLength,
  31456. base + (col + 1) + row * rowLength,
  31457. base + (col + 1) + (row + 1) * rowLength,
  31458. base + col + (row + 1) * rowLength
  31459. ];
  31460. indices.push(square[1]);
  31461. indices.push(square[2]);
  31462. indices.push(square[3]);
  31463. indices.push(square[0]);
  31464. indices.push(square[1]);
  31465. indices.push(square[3]);
  31466. }
  31467. }
  31468. // Position, normals and uvs
  31469. var position = BABYLON.Vector3.Zero();
  31470. var normal = new BABYLON.Vector3(0, 1.0, 0);
  31471. for (row = 0; row <= precision.h; row++) {
  31472. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  31473. for (col = 0; col <= precision.w; col++) {
  31474. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  31475. position.y = 0;
  31476. positions.push(position.x, position.y, position.z);
  31477. normals.push(normal.x, normal.y, normal.z);
  31478. uvs.push(col / precision.w, row / precision.h);
  31479. }
  31480. }
  31481. }
  31482. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  31483. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  31484. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  31485. }
  31486. }
  31487. // Result
  31488. var vertexData = new VertexData();
  31489. vertexData.indices = indices;
  31490. vertexData.positions = positions;
  31491. vertexData.normals = normals;
  31492. vertexData.uvs = uvs;
  31493. return vertexData;
  31494. };
  31495. /**
  31496. * Creates the VertexData of the Ground designed from a heightmap.
  31497. */
  31498. VertexData.CreateGroundFromHeightMap = function (options) {
  31499. var indices = [];
  31500. var positions = [];
  31501. var normals = [];
  31502. var uvs = [];
  31503. var row, col;
  31504. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  31505. // Vertices
  31506. for (row = 0; row <= options.subdivisions; row++) {
  31507. for (col = 0; col <= options.subdivisions; col++) {
  31508. 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));
  31509. // Compute height
  31510. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  31511. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  31512. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  31513. var r = options.buffer[pos] / 255.0;
  31514. var g = options.buffer[pos + 1] / 255.0;
  31515. var b = options.buffer[pos + 2] / 255.0;
  31516. var gradient = r * filter.r + g * filter.g + b * filter.b;
  31517. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  31518. // Add vertex
  31519. positions.push(position.x, position.y, position.z);
  31520. normals.push(0, 0, 0);
  31521. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  31522. }
  31523. }
  31524. // Indices
  31525. for (row = 0; row < options.subdivisions; row++) {
  31526. for (col = 0; col < options.subdivisions; col++) {
  31527. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  31528. indices.push(col + 1 + row * (options.subdivisions + 1));
  31529. indices.push(col + row * (options.subdivisions + 1));
  31530. indices.push(col + (row + 1) * (options.subdivisions + 1));
  31531. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  31532. indices.push(col + row * (options.subdivisions + 1));
  31533. }
  31534. }
  31535. // Normals
  31536. VertexData.ComputeNormals(positions, indices, normals);
  31537. // Result
  31538. var vertexData = new VertexData();
  31539. vertexData.indices = indices;
  31540. vertexData.positions = positions;
  31541. vertexData.normals = normals;
  31542. vertexData.uvs = uvs;
  31543. return vertexData;
  31544. };
  31545. /**
  31546. * Creates the VertexData of the Plane.
  31547. */
  31548. VertexData.CreatePlane = function (options) {
  31549. var indices = [];
  31550. var positions = [];
  31551. var normals = [];
  31552. var uvs = [];
  31553. var width = options.width || options.size || 1;
  31554. var height = options.height || options.size || 1;
  31555. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31556. // Vertices
  31557. var halfWidth = width / 2.0;
  31558. var halfHeight = height / 2.0;
  31559. positions.push(-halfWidth, -halfHeight, 0);
  31560. normals.push(0, 0, -1.0);
  31561. uvs.push(0.0, 0.0);
  31562. positions.push(halfWidth, -halfHeight, 0);
  31563. normals.push(0, 0, -1.0);
  31564. uvs.push(1.0, 0.0);
  31565. positions.push(halfWidth, halfHeight, 0);
  31566. normals.push(0, 0, -1.0);
  31567. uvs.push(1.0, 1.0);
  31568. positions.push(-halfWidth, halfHeight, 0);
  31569. normals.push(0, 0, -1.0);
  31570. uvs.push(0.0, 1.0);
  31571. // Indices
  31572. indices.push(0);
  31573. indices.push(1);
  31574. indices.push(2);
  31575. indices.push(0);
  31576. indices.push(2);
  31577. indices.push(3);
  31578. // Sides
  31579. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31580. // Result
  31581. var vertexData = new VertexData();
  31582. vertexData.indices = indices;
  31583. vertexData.positions = positions;
  31584. vertexData.normals = normals;
  31585. vertexData.uvs = uvs;
  31586. return vertexData;
  31587. };
  31588. /**
  31589. * Creates the VertexData of the Disc or regular Polygon.
  31590. */
  31591. VertexData.CreateDisc = function (options) {
  31592. var positions = new Array();
  31593. var indices = new Array();
  31594. var normals = new Array();
  31595. var uvs = new Array();
  31596. var radius = options.radius || 0.5;
  31597. var tessellation = options.tessellation || 64;
  31598. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  31599. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31600. // positions and uvs
  31601. positions.push(0, 0, 0); // disc center first
  31602. uvs.push(0.5, 0.5);
  31603. var theta = Math.PI * 2 * arc;
  31604. var step = theta / tessellation;
  31605. for (var a = 0; a < theta; a += step) {
  31606. var x = Math.cos(a);
  31607. var y = Math.sin(a);
  31608. var u = (x + 1) / 2;
  31609. var v = (1 - y) / 2;
  31610. positions.push(radius * x, radius * y, 0);
  31611. uvs.push(u, v);
  31612. }
  31613. if (arc === 1) {
  31614. positions.push(positions[3], positions[4], positions[5]); // close the circle
  31615. uvs.push(uvs[2], uvs[3]);
  31616. }
  31617. //indices
  31618. var vertexNb = positions.length / 3;
  31619. for (var i = 1; i < vertexNb - 1; i++) {
  31620. indices.push(i + 1, 0, i);
  31621. }
  31622. // result
  31623. VertexData.ComputeNormals(positions, indices, normals);
  31624. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31625. var vertexData = new VertexData();
  31626. vertexData.indices = indices;
  31627. vertexData.positions = positions;
  31628. vertexData.normals = normals;
  31629. vertexData.uvs = uvs;
  31630. return vertexData;
  31631. };
  31632. /**
  31633. * Re-creates the VertexData of the Polygon for sideOrientation.
  31634. */
  31635. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  31636. var faceUV = fUV || new Array(3);
  31637. var faceColors = fColors;
  31638. var colors = [];
  31639. // default face colors and UV if undefined
  31640. for (var f = 0; f < 3; f++) {
  31641. if (faceUV[f] === undefined) {
  31642. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31643. }
  31644. if (faceColors && faceColors[f] === undefined) {
  31645. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31646. }
  31647. }
  31648. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31649. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31650. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  31651. var indices = polygon.getIndices();
  31652. // set face colours and textures
  31653. var idx = 0;
  31654. var face = 0;
  31655. for (var index = 0; index < normals.length; index += 3) {
  31656. //Edge Face no. 1
  31657. if (Math.abs(normals[index + 1]) < 0.001) {
  31658. face = 1;
  31659. }
  31660. //Top Face no. 0
  31661. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  31662. face = 0;
  31663. }
  31664. //Bottom Face no. 2
  31665. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  31666. face = 2;
  31667. }
  31668. idx = index / 3;
  31669. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  31670. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  31671. if (faceColors) {
  31672. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  31673. }
  31674. }
  31675. // sides
  31676. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  31677. // Result
  31678. var vertexData = new VertexData();
  31679. vertexData.indices = indices;
  31680. vertexData.positions = positions;
  31681. vertexData.normals = normals;
  31682. vertexData.uvs = uvs;
  31683. if (faceColors) {
  31684. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  31685. vertexData.colors = totalColors;
  31686. }
  31687. return vertexData;
  31688. };
  31689. /**
  31690. * Creates the VertexData of the IcoSphere.
  31691. */
  31692. VertexData.CreateIcoSphere = function (options) {
  31693. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31694. var radius = options.radius || 1;
  31695. var flat = (options.flat === undefined) ? true : options.flat;
  31696. var subdivisions = options.subdivisions || 4;
  31697. var radiusX = options.radiusX || radius;
  31698. var radiusY = options.radiusY || radius;
  31699. var radiusZ = options.radiusZ || radius;
  31700. var t = (1 + Math.sqrt(5)) / 2;
  31701. // 12 vertex x,y,z
  31702. var ico_vertices = [
  31703. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  31704. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  31705. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  31706. ];
  31707. // index of 3 vertex makes a face of icopshere
  31708. var ico_indices = [
  31709. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  31710. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  31711. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  31712. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  31713. ];
  31714. // vertex for uv have aliased position, not for UV
  31715. var vertices_unalias_id = [
  31716. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  31717. // vertex alias
  31718. 0,
  31719. 2,
  31720. 3,
  31721. 3,
  31722. 3,
  31723. 4,
  31724. 7,
  31725. 8,
  31726. 9,
  31727. 9,
  31728. 10,
  31729. 11 // 23: B + 12
  31730. ];
  31731. // uv as integer step (not pixels !)
  31732. var ico_vertexuv = [
  31733. 5, 1, 3, 1, 6, 4, 0, 0,
  31734. 5, 3, 4, 2, 2, 2, 4, 0,
  31735. 2, 0, 1, 1, 6, 0, 6, 2,
  31736. // vertex alias (for same vertex on different faces)
  31737. 0, 4,
  31738. 3, 3,
  31739. 4, 4,
  31740. 3, 1,
  31741. 4, 2,
  31742. 4, 4,
  31743. 0, 2,
  31744. 1, 1,
  31745. 2, 2,
  31746. 3, 3,
  31747. 1, 3,
  31748. 2, 4 // 23: B + 12
  31749. ];
  31750. // Vertices[0, 1, ...9, A, B] : position on UV plane
  31751. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  31752. // First island of uv mapping
  31753. // v = 4h 3+ 2
  31754. // v = 3h 9+ 4
  31755. // v = 2h 9+ 5 B
  31756. // v = 1h 9 1 0
  31757. // v = 0h 3 8 7 A
  31758. // u = 0 1 2 3 4 5 6 *a
  31759. // Second island of uv mapping
  31760. // v = 4h 0+ B+ 4+
  31761. // v = 3h A+ 2+
  31762. // v = 2h 7+ 6 3+
  31763. // v = 1h 8+ 3+
  31764. // v = 0h
  31765. // u = 0 1 2 3 4 5 6 *a
  31766. // Face layout on texture UV mapping
  31767. // ============
  31768. // \ 4 /\ 16 / ======
  31769. // \ / \ / /\ 11 /
  31770. // \/ 7 \/ / \ /
  31771. // ======= / 10 \/
  31772. // /\ 17 /\ =======
  31773. // / \ / \ \ 15 /\
  31774. // / 8 \/ 12 \ \ / \
  31775. // ============ \/ 6 \
  31776. // \ 18 /\ ============
  31777. // \ / \ \ 5 /\ 0 /
  31778. // \/ 13 \ \ / \ /
  31779. // ======= \/ 1 \/
  31780. // =============
  31781. // /\ 19 /\ 2 /\
  31782. // / \ / \ / \
  31783. // / 14 \/ 9 \/ 3 \
  31784. // ===================
  31785. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  31786. var ustep = 138 / 1024;
  31787. var vstep = 239 / 1024;
  31788. var uoffset = 60 / 1024;
  31789. var voffset = 26 / 1024;
  31790. // Second island should have margin, not to touch the first island
  31791. // avoid any borderline artefact in pixel rounding
  31792. var island_u_offset = -40 / 1024;
  31793. var island_v_offset = +20 / 1024;
  31794. // face is either island 0 or 1 :
  31795. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  31796. var island = [
  31797. 0, 0, 0, 0, 1,
  31798. 0, 0, 1, 1, 0,
  31799. 0, 0, 1, 1, 0,
  31800. 0, 1, 1, 1, 0 // 15 - 19
  31801. ];
  31802. var indices = new Array();
  31803. var positions = new Array();
  31804. var normals = new Array();
  31805. var uvs = new Array();
  31806. var current_indice = 0;
  31807. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  31808. var face_vertex_pos = new Array(3);
  31809. var face_vertex_uv = new Array(3);
  31810. var v012;
  31811. for (v012 = 0; v012 < 3; v012++) {
  31812. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  31813. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  31814. }
  31815. // create all with normals
  31816. for (var face = 0; face < 20; face++) {
  31817. // 3 vertex per face
  31818. for (v012 = 0; v012 < 3; v012++) {
  31819. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  31820. var v_id = ico_indices[3 * face + v012];
  31821. // vertex have 3D position (x,y,z)
  31822. 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]);
  31823. // Normalize to get normal, then scale to radius
  31824. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  31825. // uv Coordinates from vertex ID
  31826. 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);
  31827. }
  31828. // Subdivide the face (interpolate pos, norm, uv)
  31829. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  31830. // - norm is linear interpolation of vertex corner normal
  31831. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  31832. // - uv is linear interpolation
  31833. //
  31834. // Topology is as below for sub-divide by 2
  31835. // vertex shown as v0,v1,v2
  31836. // interp index is i1 to progress in range [v0,v1[
  31837. // interp index is i2 to progress in range [v0,v2[
  31838. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  31839. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  31840. //
  31841. //
  31842. // i2 v2
  31843. // ^ ^
  31844. // / / \
  31845. // / / \
  31846. // / / \
  31847. // / / (0,1) \
  31848. // / #---------\
  31849. // / / \ (0,0)'/ \
  31850. // / / \ / \
  31851. // / / \ / \
  31852. // / / (0,0) \ / (1,0) \
  31853. // / #---------#---------\
  31854. // v0 v1
  31855. //
  31856. // --------------------> i1
  31857. //
  31858. // interp of (i1,i2):
  31859. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  31860. // along i1 : lerp(x0,x1, i1/(S-i2))
  31861. //
  31862. // centroid of triangle is needed to get help normal computation
  31863. // (c1,c2) are used for centroid location
  31864. var interp_vertex = function (i1, i2, c1, c2) {
  31865. // vertex is interpolated from
  31866. // - face_vertex_pos[0..2]
  31867. // - face_vertex_uv[0..2]
  31868. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  31869. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  31870. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  31871. pos_interp.normalize();
  31872. var vertex_normal;
  31873. if (flat) {
  31874. // in flat mode, recalculate normal as face centroid normal
  31875. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  31876. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  31877. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  31878. }
  31879. else {
  31880. // in smooth mode, recalculate normal from each single vertex position
  31881. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  31882. }
  31883. // Vertex normal need correction due to X,Y,Z radius scaling
  31884. vertex_normal.x /= radiusX;
  31885. vertex_normal.y /= radiusY;
  31886. vertex_normal.z /= radiusZ;
  31887. vertex_normal.normalize();
  31888. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  31889. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  31890. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  31891. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  31892. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  31893. uvs.push(uv_interp.x, uv_interp.y);
  31894. // push each vertex has member of a face
  31895. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  31896. indices.push(current_indice);
  31897. current_indice++;
  31898. };
  31899. for (var i2 = 0; i2 < subdivisions; i2++) {
  31900. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  31901. // face : (i1,i2) for /\ :
  31902. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  31903. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  31904. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  31905. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  31906. if (i1 + i2 + 1 < subdivisions) {
  31907. // face : (i1,i2)' for \/ :
  31908. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  31909. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  31910. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  31911. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  31912. }
  31913. }
  31914. }
  31915. }
  31916. // Sides
  31917. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31918. // Result
  31919. var vertexData = new VertexData();
  31920. vertexData.indices = indices;
  31921. vertexData.positions = positions;
  31922. vertexData.normals = normals;
  31923. vertexData.uvs = uvs;
  31924. return vertexData;
  31925. };
  31926. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  31927. /**
  31928. * Creates the VertexData of the Polyhedron.
  31929. */
  31930. VertexData.CreatePolyhedron = function (options) {
  31931. // provided polyhedron types :
  31932. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  31933. // 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)
  31934. var polyhedra = [];
  31935. 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]] };
  31936. 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]] };
  31937. polyhedra[2] = {
  31938. 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]],
  31939. 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]]
  31940. };
  31941. polyhedra[3] = {
  31942. 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]],
  31943. 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]]
  31944. };
  31945. polyhedra[4] = {
  31946. 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]],
  31947. 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]]
  31948. };
  31949. 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]] };
  31950. 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]] };
  31951. 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]] };
  31952. 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]] };
  31953. 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]] };
  31954. 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]] };
  31955. 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]] };
  31956. 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]] };
  31957. 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]] };
  31958. polyhedra[14] = {
  31959. 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]],
  31960. 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]]
  31961. };
  31962. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  31963. var size = options.size;
  31964. var sizeX = options.sizeX || size || 1;
  31965. var sizeY = options.sizeY || size || 1;
  31966. var sizeZ = options.sizeZ || size || 1;
  31967. var data = options.custom || polyhedra[type];
  31968. var nbfaces = data.face.length;
  31969. var faceUV = options.faceUV || new Array(nbfaces);
  31970. var faceColors = options.faceColors;
  31971. var flat = (options.flat === undefined) ? true : options.flat;
  31972. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31973. var positions = new Array();
  31974. var indices = new Array();
  31975. var normals = new Array();
  31976. var uvs = new Array();
  31977. var colors = new Array();
  31978. var index = 0;
  31979. var faceIdx = 0; // face cursor in the array "indexes"
  31980. var indexes = new Array();
  31981. var i = 0;
  31982. var f = 0;
  31983. var u, v, ang, x, y, tmp;
  31984. // default face colors and UV if undefined
  31985. if (flat) {
  31986. for (f = 0; f < nbfaces; f++) {
  31987. if (faceColors && faceColors[f] === undefined) {
  31988. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31989. }
  31990. if (faceUV && faceUV[f] === undefined) {
  31991. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31992. }
  31993. }
  31994. }
  31995. if (!flat) {
  31996. for (i = 0; i < data.vertex.length; i++) {
  31997. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  31998. uvs.push(0, 0);
  31999. }
  32000. for (f = 0; f < nbfaces; f++) {
  32001. for (i = 0; i < data.face[f].length - 2; i++) {
  32002. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  32003. }
  32004. }
  32005. }
  32006. else {
  32007. for (f = 0; f < nbfaces; f++) {
  32008. var fl = data.face[f].length; // number of vertices of the current face
  32009. ang = 2 * Math.PI / fl;
  32010. x = 0.5 * Math.tan(ang / 2);
  32011. y = 0.5;
  32012. // positions, uvs, colors
  32013. for (i = 0; i < fl; i++) {
  32014. // positions
  32015. 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);
  32016. indexes.push(index);
  32017. index++;
  32018. // uvs
  32019. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  32020. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  32021. uvs.push(u, v);
  32022. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  32023. y = x * Math.sin(ang) + y * Math.cos(ang);
  32024. x = tmp;
  32025. // colors
  32026. if (faceColors) {
  32027. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  32028. }
  32029. }
  32030. // indices from indexes
  32031. for (i = 0; i < fl - 2; i++) {
  32032. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  32033. }
  32034. faceIdx += fl;
  32035. }
  32036. }
  32037. VertexData.ComputeNormals(positions, indices, normals);
  32038. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32039. var vertexData = new VertexData();
  32040. vertexData.positions = positions;
  32041. vertexData.indices = indices;
  32042. vertexData.normals = normals;
  32043. vertexData.uvs = uvs;
  32044. if (faceColors && flat) {
  32045. vertexData.colors = colors;
  32046. }
  32047. return vertexData;
  32048. };
  32049. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  32050. /**
  32051. * Creates the VertexData of the Torus Knot.
  32052. */
  32053. VertexData.CreateTorusKnot = function (options) {
  32054. var indices = new Array();
  32055. var positions = new Array();
  32056. var normals = new Array();
  32057. var uvs = new Array();
  32058. var radius = options.radius || 2;
  32059. var tube = options.tube || 0.5;
  32060. var radialSegments = options.radialSegments || 32;
  32061. var tubularSegments = options.tubularSegments || 32;
  32062. var p = options.p || 2;
  32063. var q = options.q || 3;
  32064. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32065. // Helper
  32066. var getPos = function (angle) {
  32067. var cu = Math.cos(angle);
  32068. var su = Math.sin(angle);
  32069. var quOverP = q / p * angle;
  32070. var cs = Math.cos(quOverP);
  32071. var tx = radius * (2 + cs) * 0.5 * cu;
  32072. var ty = radius * (2 + cs) * su * 0.5;
  32073. var tz = radius * Math.sin(quOverP) * 0.5;
  32074. return new BABYLON.Vector3(tx, ty, tz);
  32075. };
  32076. // Vertices
  32077. var i;
  32078. var j;
  32079. for (i = 0; i <= radialSegments; i++) {
  32080. var modI = i % radialSegments;
  32081. var u = modI / radialSegments * 2 * p * Math.PI;
  32082. var p1 = getPos(u);
  32083. var p2 = getPos(u + 0.01);
  32084. var tang = p2.subtract(p1);
  32085. var n = p2.add(p1);
  32086. var bitan = BABYLON.Vector3.Cross(tang, n);
  32087. n = BABYLON.Vector3.Cross(bitan, tang);
  32088. bitan.normalize();
  32089. n.normalize();
  32090. for (j = 0; j < tubularSegments; j++) {
  32091. var modJ = j % tubularSegments;
  32092. var v = modJ / tubularSegments * 2 * Math.PI;
  32093. var cx = -tube * Math.cos(v);
  32094. var cy = tube * Math.sin(v);
  32095. positions.push(p1.x + cx * n.x + cy * bitan.x);
  32096. positions.push(p1.y + cx * n.y + cy * bitan.y);
  32097. positions.push(p1.z + cx * n.z + cy * bitan.z);
  32098. uvs.push(i / radialSegments);
  32099. uvs.push(j / tubularSegments);
  32100. }
  32101. }
  32102. for (i = 0; i < radialSegments; i++) {
  32103. for (j = 0; j < tubularSegments; j++) {
  32104. var jNext = (j + 1) % tubularSegments;
  32105. var a = i * tubularSegments + j;
  32106. var b = (i + 1) * tubularSegments + j;
  32107. var c = (i + 1) * tubularSegments + jNext;
  32108. var d = i * tubularSegments + jNext;
  32109. indices.push(d);
  32110. indices.push(b);
  32111. indices.push(a);
  32112. indices.push(d);
  32113. indices.push(c);
  32114. indices.push(b);
  32115. }
  32116. }
  32117. // Normals
  32118. VertexData.ComputeNormals(positions, indices, normals);
  32119. // Sides
  32120. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32121. // Result
  32122. var vertexData = new VertexData();
  32123. vertexData.indices = indices;
  32124. vertexData.positions = positions;
  32125. vertexData.normals = normals;
  32126. vertexData.uvs = uvs;
  32127. return vertexData;
  32128. };
  32129. // Tools
  32130. /**
  32131. * @param {any} - positions (number[] or Float32Array)
  32132. * @param {any} - indices (number[] or Uint16Array)
  32133. * @param {any} - normals (number[] or Float32Array)
  32134. * options (optional) :
  32135. * facetPositions : optional array of facet positions (vector3)
  32136. * facetNormals : optional array of facet normals (vector3)
  32137. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  32138. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  32139. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  32140. * bbSize : optional bounding box size data, required for facetPartitioning computation
  32141. * bInfo : optional bounding info, required for facetPartitioning computation
  32142. * useRightHandedSystem: optional boolean to for right handed system computation
  32143. * depthSort : optional boolean to enable the facet depth sort computation
  32144. * distanceTo : optional Vector3 to compute the facet depth from this location
  32145. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  32146. */
  32147. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  32148. // temporary scalar variables
  32149. var index = 0; // facet index
  32150. var p1p2x = 0.0; // p1p2 vector x coordinate
  32151. var p1p2y = 0.0; // p1p2 vector y coordinate
  32152. var p1p2z = 0.0; // p1p2 vector z coordinate
  32153. var p3p2x = 0.0; // p3p2 vector x coordinate
  32154. var p3p2y = 0.0; // p3p2 vector y coordinate
  32155. var p3p2z = 0.0; // p3p2 vector z coordinate
  32156. var faceNormalx = 0.0; // facet normal x coordinate
  32157. var faceNormaly = 0.0; // facet normal y coordinate
  32158. var faceNormalz = 0.0; // facet normal z coordinate
  32159. var length = 0.0; // facet normal length before normalization
  32160. var v1x = 0; // vector1 x index in the positions array
  32161. var v1y = 0; // vector1 y index in the positions array
  32162. var v1z = 0; // vector1 z index in the positions array
  32163. var v2x = 0; // vector2 x index in the positions array
  32164. var v2y = 0; // vector2 y index in the positions array
  32165. var v2z = 0; // vector2 z index in the positions array
  32166. var v3x = 0; // vector3 x index in the positions array
  32167. var v3y = 0; // vector3 y index in the positions array
  32168. var v3z = 0; // vector3 z index in the positions array
  32169. var computeFacetNormals = false;
  32170. var computeFacetPositions = false;
  32171. var computeFacetPartitioning = false;
  32172. var computeDepthSort = false;
  32173. var faceNormalSign = 1;
  32174. var ratio = 0;
  32175. var distanceTo = null;
  32176. if (options) {
  32177. computeFacetNormals = (options.facetNormals) ? true : false;
  32178. computeFacetPositions = (options.facetPositions) ? true : false;
  32179. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  32180. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  32181. ratio = options.ratio || 0;
  32182. computeDepthSort = (options.depthSort) ? true : false;
  32183. distanceTo = (options.distanceTo);
  32184. if (computeDepthSort) {
  32185. if (distanceTo === undefined) {
  32186. distanceTo = BABYLON.Vector3.Zero();
  32187. }
  32188. var depthSortedFacets = options.depthSortedFacets;
  32189. }
  32190. }
  32191. // facetPartitioning reinit if needed
  32192. var xSubRatio = 0;
  32193. var ySubRatio = 0;
  32194. var zSubRatio = 0;
  32195. var subSq = 0;
  32196. if (computeFacetPartitioning && options && options.bbSize) {
  32197. var ox = 0; // X partitioning index for facet position
  32198. var oy = 0; // Y partinioning index for facet position
  32199. var oz = 0; // Z partinioning index for facet position
  32200. var b1x = 0; // X partitioning index for facet v1 vertex
  32201. var b1y = 0; // Y partitioning index for facet v1 vertex
  32202. var b1z = 0; // z partitioning index for facet v1 vertex
  32203. var b2x = 0; // X partitioning index for facet v2 vertex
  32204. var b2y = 0; // Y partitioning index for facet v2 vertex
  32205. var b2z = 0; // Z partitioning index for facet v2 vertex
  32206. var b3x = 0; // X partitioning index for facet v3 vertex
  32207. var b3y = 0; // Y partitioning index for facet v3 vertex
  32208. var b3z = 0; // Z partitioning index for facet v3 vertex
  32209. var block_idx_o = 0; // facet barycenter block index
  32210. var block_idx_v1 = 0; // v1 vertex block index
  32211. var block_idx_v2 = 0; // v2 vertex block index
  32212. var block_idx_v3 = 0; // v3 vertex block index
  32213. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  32214. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  32215. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  32216. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  32217. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  32218. subSq = options.subDiv.max * options.subDiv.max;
  32219. options.facetPartitioning.length = 0;
  32220. }
  32221. // reset the normals
  32222. for (index = 0; index < positions.length; index++) {
  32223. normals[index] = 0.0;
  32224. }
  32225. // Loop : 1 indice triplet = 1 facet
  32226. var nbFaces = (indices.length / 3) | 0;
  32227. for (index = 0; index < nbFaces; index++) {
  32228. // get the indexes of the coordinates of each vertex of the facet
  32229. v1x = indices[index * 3] * 3;
  32230. v1y = v1x + 1;
  32231. v1z = v1x + 2;
  32232. v2x = indices[index * 3 + 1] * 3;
  32233. v2y = v2x + 1;
  32234. v2z = v2x + 2;
  32235. v3x = indices[index * 3 + 2] * 3;
  32236. v3y = v3x + 1;
  32237. v3z = v3x + 2;
  32238. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  32239. p1p2y = positions[v1y] - positions[v2y];
  32240. p1p2z = positions[v1z] - positions[v2z];
  32241. p3p2x = positions[v3x] - positions[v2x];
  32242. p3p2y = positions[v3y] - positions[v2y];
  32243. p3p2z = positions[v3z] - positions[v2z];
  32244. // compute the face normal with the cross product
  32245. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  32246. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  32247. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  32248. // normalize this normal and store it in the array facetData
  32249. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  32250. length = (length === 0) ? 1.0 : length;
  32251. faceNormalx /= length;
  32252. faceNormaly /= length;
  32253. faceNormalz /= length;
  32254. if (computeFacetNormals && options) {
  32255. options.facetNormals[index].x = faceNormalx;
  32256. options.facetNormals[index].y = faceNormaly;
  32257. options.facetNormals[index].z = faceNormalz;
  32258. }
  32259. if (computeFacetPositions && options) {
  32260. // compute and the facet barycenter coordinates in the array facetPositions
  32261. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  32262. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  32263. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  32264. }
  32265. if (computeFacetPartitioning && options) {
  32266. // store the facet indexes in arrays in the main facetPartitioning array :
  32267. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  32268. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  32269. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  32270. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  32271. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  32272. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  32273. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  32274. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  32275. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  32276. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  32277. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  32278. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  32279. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  32280. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  32281. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  32282. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  32283. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  32284. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  32285. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  32286. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  32287. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  32288. // push each facet index in each block containing the vertex
  32289. options.facetPartitioning[block_idx_v1].push(index);
  32290. if (block_idx_v2 != block_idx_v1) {
  32291. options.facetPartitioning[block_idx_v2].push(index);
  32292. }
  32293. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  32294. options.facetPartitioning[block_idx_v3].push(index);
  32295. }
  32296. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  32297. options.facetPartitioning[block_idx_o].push(index);
  32298. }
  32299. }
  32300. if (computeDepthSort && options && options.facetPositions) {
  32301. var dsf = depthSortedFacets[index];
  32302. dsf.ind = index * 3;
  32303. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  32304. }
  32305. // compute the normals anyway
  32306. normals[v1x] += faceNormalx; // accumulate all the normals per face
  32307. normals[v1y] += faceNormaly;
  32308. normals[v1z] += faceNormalz;
  32309. normals[v2x] += faceNormalx;
  32310. normals[v2y] += faceNormaly;
  32311. normals[v2z] += faceNormalz;
  32312. normals[v3x] += faceNormalx;
  32313. normals[v3y] += faceNormaly;
  32314. normals[v3z] += faceNormalz;
  32315. }
  32316. // last normalization of each normal
  32317. for (index = 0; index < normals.length / 3; index++) {
  32318. faceNormalx = normals[index * 3];
  32319. faceNormaly = normals[index * 3 + 1];
  32320. faceNormalz = normals[index * 3 + 2];
  32321. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  32322. length = (length === 0) ? 1.0 : length;
  32323. faceNormalx /= length;
  32324. faceNormaly /= length;
  32325. faceNormalz /= length;
  32326. normals[index * 3] = faceNormalx;
  32327. normals[index * 3 + 1] = faceNormaly;
  32328. normals[index * 3 + 2] = faceNormalz;
  32329. }
  32330. };
  32331. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  32332. var li = indices.length;
  32333. var ln = normals.length;
  32334. var i;
  32335. var n;
  32336. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32337. switch (sideOrientation) {
  32338. case BABYLON.Mesh.FRONTSIDE:
  32339. // nothing changed
  32340. break;
  32341. case BABYLON.Mesh.BACKSIDE:
  32342. var tmp;
  32343. // indices
  32344. for (i = 0; i < li; i += 3) {
  32345. tmp = indices[i];
  32346. indices[i] = indices[i + 2];
  32347. indices[i + 2] = tmp;
  32348. }
  32349. // normals
  32350. for (n = 0; n < ln; n++) {
  32351. normals[n] = -normals[n];
  32352. }
  32353. break;
  32354. case BABYLON.Mesh.DOUBLESIDE:
  32355. // positions
  32356. var lp = positions.length;
  32357. var l = lp / 3;
  32358. for (var p = 0; p < lp; p++) {
  32359. positions[lp + p] = positions[p];
  32360. }
  32361. // indices
  32362. for (i = 0; i < li; i += 3) {
  32363. indices[i + li] = indices[i + 2] + l;
  32364. indices[i + 1 + li] = indices[i + 1] + l;
  32365. indices[i + 2 + li] = indices[i] + l;
  32366. }
  32367. // normals
  32368. for (n = 0; n < ln; n++) {
  32369. normals[ln + n] = -normals[n];
  32370. }
  32371. // uvs
  32372. var lu = uvs.length;
  32373. var u = 0;
  32374. for (u = 0; u < lu; u++) {
  32375. uvs[u + lu] = uvs[u];
  32376. }
  32377. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  32378. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  32379. u = 0;
  32380. for (i = 0; i < lu / 2; i++) {
  32381. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  32382. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  32383. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  32384. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  32385. u += 2;
  32386. }
  32387. break;
  32388. }
  32389. };
  32390. /**
  32391. * Creates a new VertexData from the imported parameters.
  32392. */
  32393. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  32394. var vertexData = new VertexData();
  32395. // positions
  32396. var positions = parsedVertexData.positions;
  32397. if (positions) {
  32398. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  32399. }
  32400. // normals
  32401. var normals = parsedVertexData.normals;
  32402. if (normals) {
  32403. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  32404. }
  32405. // tangents
  32406. var tangents = parsedVertexData.tangents;
  32407. if (tangents) {
  32408. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  32409. }
  32410. // uvs
  32411. var uvs = parsedVertexData.uvs;
  32412. if (uvs) {
  32413. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  32414. }
  32415. // uv2s
  32416. var uv2s = parsedVertexData.uv2s;
  32417. if (uv2s) {
  32418. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  32419. }
  32420. // uv3s
  32421. var uv3s = parsedVertexData.uv3s;
  32422. if (uv3s) {
  32423. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  32424. }
  32425. // uv4s
  32426. var uv4s = parsedVertexData.uv4s;
  32427. if (uv4s) {
  32428. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  32429. }
  32430. // uv5s
  32431. var uv5s = parsedVertexData.uv5s;
  32432. if (uv5s) {
  32433. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  32434. }
  32435. // uv6s
  32436. var uv6s = parsedVertexData.uv6s;
  32437. if (uv6s) {
  32438. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  32439. }
  32440. // colors
  32441. var colors = parsedVertexData.colors;
  32442. if (colors) {
  32443. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  32444. }
  32445. // matricesIndices
  32446. var matricesIndices = parsedVertexData.matricesIndices;
  32447. if (matricesIndices) {
  32448. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  32449. }
  32450. // matricesWeights
  32451. var matricesWeights = parsedVertexData.matricesWeights;
  32452. if (matricesWeights) {
  32453. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  32454. }
  32455. // indices
  32456. var indices = parsedVertexData.indices;
  32457. if (indices) {
  32458. vertexData.indices = indices;
  32459. }
  32460. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  32461. };
  32462. return VertexData;
  32463. }());
  32464. BABYLON.VertexData = VertexData;
  32465. })(BABYLON || (BABYLON = {}));
  32466. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  32467. var BABYLON;
  32468. (function (BABYLON) {
  32469. /**
  32470. * Class used to store geometry data (vertex buffers + index buffer)
  32471. */
  32472. var Geometry = /** @class */ (function () {
  32473. /**
  32474. * Creates a new geometry
  32475. * @param id defines the unique ID
  32476. * @param scene defines the hosting scene
  32477. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  32478. * @param updatable defines if geometry must be updatable (false by default)
  32479. * @param mesh defines the mesh that will be associated with the geometry
  32480. */
  32481. function Geometry(id, scene, vertexData, updatable, mesh) {
  32482. if (updatable === void 0) { updatable = false; }
  32483. if (mesh === void 0) { mesh = null; }
  32484. /**
  32485. * Gets the delay loading state of the geometry (none by default which means not delayed)
  32486. */
  32487. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  32488. this._totalVertices = 0;
  32489. this._isDisposed = false;
  32490. this._indexBufferIsUpdatable = false;
  32491. this.id = id;
  32492. this._engine = scene.getEngine();
  32493. this._meshes = [];
  32494. this._scene = scene;
  32495. //Init vertex buffer cache
  32496. this._vertexBuffers = {};
  32497. this._indices = [];
  32498. this._updatable = updatable;
  32499. // vertexData
  32500. if (vertexData) {
  32501. this.setAllVerticesData(vertexData, updatable);
  32502. }
  32503. else {
  32504. this._totalVertices = 0;
  32505. this._indices = [];
  32506. }
  32507. if (this._engine.getCaps().vertexArrayObject) {
  32508. this._vertexArrayObjects = {};
  32509. }
  32510. // applyToMesh
  32511. if (mesh) {
  32512. if (mesh.getClassName() === "LinesMesh") {
  32513. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  32514. this.updateExtend();
  32515. }
  32516. this.applyToMesh(mesh);
  32517. mesh.computeWorldMatrix(true);
  32518. }
  32519. }
  32520. Object.defineProperty(Geometry.prototype, "boundingBias", {
  32521. /**
  32522. * Gets or sets 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
  32523. */
  32524. get: function () {
  32525. return this._boundingBias;
  32526. },
  32527. /**
  32528. * Gets or sets 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
  32529. */
  32530. set: function (value) {
  32531. if (this._boundingBias && this._boundingBias.equals(value)) {
  32532. return;
  32533. }
  32534. this._boundingBias = value.clone();
  32535. this.updateBoundingInfo(true, null);
  32536. },
  32537. enumerable: true,
  32538. configurable: true
  32539. });
  32540. /**
  32541. * Static function used to attach a new empty geometry to a mesh
  32542. * @param mesh defines the mesh to attach the geometry to
  32543. * @returns the new {BABYLON.Geometry}
  32544. */
  32545. Geometry.CreateGeometryForMesh = function (mesh) {
  32546. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  32547. geometry.applyToMesh(mesh);
  32548. return geometry;
  32549. };
  32550. Object.defineProperty(Geometry.prototype, "extend", {
  32551. /**
  32552. * Gets the current extend of the geometry
  32553. */
  32554. get: function () {
  32555. return this._extend;
  32556. },
  32557. enumerable: true,
  32558. configurable: true
  32559. });
  32560. /**
  32561. * Gets the hosting scene
  32562. * @returns the hosting {BABYLON.Scene}
  32563. */
  32564. Geometry.prototype.getScene = function () {
  32565. return this._scene;
  32566. };
  32567. /**
  32568. * Gets the hosting engine
  32569. * @returns the hosting {BABYLON.Engine}
  32570. */
  32571. Geometry.prototype.getEngine = function () {
  32572. return this._engine;
  32573. };
  32574. /**
  32575. * Defines if the geometry is ready to use
  32576. * @returns true if the geometry is ready to be used
  32577. */
  32578. Geometry.prototype.isReady = function () {
  32579. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  32580. };
  32581. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  32582. /**
  32583. * Gets a value indicating that the geometry should not be serialized
  32584. */
  32585. get: function () {
  32586. for (var index = 0; index < this._meshes.length; index++) {
  32587. if (!this._meshes[index].doNotSerialize) {
  32588. return false;
  32589. }
  32590. }
  32591. return true;
  32592. },
  32593. enumerable: true,
  32594. configurable: true
  32595. });
  32596. /** @ignore */
  32597. Geometry.prototype._rebuild = function () {
  32598. if (this._vertexArrayObjects) {
  32599. this._vertexArrayObjects = {};
  32600. }
  32601. // Index buffer
  32602. if (this._meshes.length !== 0 && this._indices) {
  32603. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  32604. }
  32605. // Vertex buffers
  32606. for (var key in this._vertexBuffers) {
  32607. var vertexBuffer = this._vertexBuffers[key];
  32608. vertexBuffer._rebuild();
  32609. }
  32610. };
  32611. /**
  32612. * Affects all gemetry data in one call
  32613. * @param vertexData defines the geometry data
  32614. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  32615. */
  32616. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  32617. vertexData.applyToGeometry(this, updatable);
  32618. this.notifyUpdate();
  32619. };
  32620. /**
  32621. * Set specific vertex data
  32622. * @param kind defines the data kind (Position, normal, etc...)
  32623. * @param data defines the vertex data to use
  32624. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  32625. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  32626. */
  32627. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32628. if (updatable === void 0) { updatable = false; }
  32629. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  32630. this.setVerticesBuffer(buffer);
  32631. };
  32632. /**
  32633. * Removes a specific vertex data
  32634. * @param kind defines the data kind (Position, normal, etc...)
  32635. */
  32636. Geometry.prototype.removeVerticesData = function (kind) {
  32637. if (this._vertexBuffers[kind]) {
  32638. this._vertexBuffers[kind].dispose();
  32639. delete this._vertexBuffers[kind];
  32640. }
  32641. };
  32642. /**
  32643. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  32644. * @param buffer defines the vertex buffer to use
  32645. */
  32646. Geometry.prototype.setVerticesBuffer = function (buffer) {
  32647. var kind = buffer.getKind();
  32648. if (this._vertexBuffers[kind]) {
  32649. this._vertexBuffers[kind].dispose();
  32650. }
  32651. this._vertexBuffers[kind] = buffer;
  32652. if (kind === BABYLON.VertexBuffer.PositionKind) {
  32653. var data = buffer.getData();
  32654. var stride = buffer.getStrideSize();
  32655. this._totalVertices = data.length / stride;
  32656. this.updateExtend(data, stride);
  32657. this._resetPointsArrayCache();
  32658. var meshes = this._meshes;
  32659. var numOfMeshes = meshes.length;
  32660. for (var index = 0; index < numOfMeshes; index++) {
  32661. var mesh = meshes[index];
  32662. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32663. mesh._createGlobalSubMesh(false);
  32664. mesh.computeWorldMatrix(true);
  32665. }
  32666. }
  32667. this.notifyUpdate(kind);
  32668. if (this._vertexArrayObjects) {
  32669. this._disposeVertexArrayObjects();
  32670. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  32671. }
  32672. };
  32673. /**
  32674. * Update a specific vertex buffer
  32675. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  32676. * It will do nothing if the buffer is not updatable
  32677. * @param kind defines the data kind (Position, normal, etc...)
  32678. * @param data defines the data to use
  32679. * @param offset defines the offset in the target buffer where to store the data
  32680. */
  32681. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  32682. var vertexBuffer = this.getVertexBuffer(kind);
  32683. if (!vertexBuffer) {
  32684. return;
  32685. }
  32686. vertexBuffer.updateDirectly(data, offset);
  32687. this.notifyUpdate(kind);
  32688. };
  32689. /**
  32690. * Update a specific vertex buffer
  32691. * This function will create a new buffer if the current one is not updatable
  32692. * @param kind defines the data kind (Position, normal, etc...)
  32693. * @param data defines the data to use
  32694. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  32695. */
  32696. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  32697. if (updateExtends === void 0) { updateExtends = false; }
  32698. var vertexBuffer = this.getVertexBuffer(kind);
  32699. if (!vertexBuffer) {
  32700. return;
  32701. }
  32702. vertexBuffer.update(data);
  32703. if (kind === BABYLON.VertexBuffer.PositionKind) {
  32704. var stride = vertexBuffer.getStrideSize();
  32705. this._totalVertices = data.length / stride;
  32706. this.updateBoundingInfo(updateExtends, data);
  32707. }
  32708. this.notifyUpdate(kind);
  32709. };
  32710. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  32711. if (updateExtends) {
  32712. this.updateExtend(data);
  32713. }
  32714. var meshes = this._meshes;
  32715. var numOfMeshes = meshes.length;
  32716. this._resetPointsArrayCache();
  32717. for (var index = 0; index < numOfMeshes; index++) {
  32718. var mesh = meshes[index];
  32719. if (updateExtends) {
  32720. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32721. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  32722. var subMesh = mesh.subMeshes[subIndex];
  32723. subMesh.refreshBoundingInfo();
  32724. }
  32725. }
  32726. }
  32727. };
  32728. /** @ignore */
  32729. Geometry.prototype._bind = function (effect, indexToBind) {
  32730. if (!effect) {
  32731. return;
  32732. }
  32733. if (indexToBind === undefined) {
  32734. indexToBind = this._indexBuffer;
  32735. }
  32736. var vbs = this.getVertexBuffers();
  32737. if (!vbs) {
  32738. return;
  32739. }
  32740. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  32741. this._engine.bindBuffers(vbs, indexToBind, effect);
  32742. return;
  32743. }
  32744. // Using VAO
  32745. if (!this._vertexArrayObjects[effect.key]) {
  32746. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  32747. }
  32748. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  32749. };
  32750. /**
  32751. * Gets total number of vertices
  32752. * @returns the total number of vertices
  32753. */
  32754. Geometry.prototype.getTotalVertices = function () {
  32755. if (!this.isReady()) {
  32756. return 0;
  32757. }
  32758. return this._totalVertices;
  32759. };
  32760. /**
  32761. * Gets a specific vertex data attached to this geometry
  32762. * @param kind defines the data kind (Position, normal, etc...)
  32763. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  32764. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  32765. * @returns a float array containing vertex data
  32766. */
  32767. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  32768. var vertexBuffer = this.getVertexBuffer(kind);
  32769. if (!vertexBuffer) {
  32770. return null;
  32771. }
  32772. var orig = vertexBuffer.getData();
  32773. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  32774. return orig;
  32775. }
  32776. else {
  32777. var len = orig.length;
  32778. var copy = [];
  32779. for (var i = 0; i < len; i++) {
  32780. copy.push(orig[i]);
  32781. }
  32782. return copy;
  32783. }
  32784. };
  32785. /**
  32786. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  32787. * @param kind defines the data kind (Position, normal, etc...)
  32788. * @returns true if the vertex buffer with the specified kind is updatable
  32789. */
  32790. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  32791. var vb = this._vertexBuffers[kind];
  32792. if (!vb) {
  32793. return false;
  32794. }
  32795. return vb.isUpdatable();
  32796. };
  32797. /**
  32798. * Gets a specific vertex buffer
  32799. * @param kind defines the data kind (Position, normal, etc...)
  32800. * @returns a {BABYLON.VertexBuffer}
  32801. */
  32802. Geometry.prototype.getVertexBuffer = function (kind) {
  32803. if (!this.isReady()) {
  32804. return null;
  32805. }
  32806. return this._vertexBuffers[kind];
  32807. };
  32808. /**
  32809. * Returns all vertex buffers
  32810. * @return an object holding all vertex buffers indexed by kind
  32811. */
  32812. Geometry.prototype.getVertexBuffers = function () {
  32813. if (!this.isReady()) {
  32814. return null;
  32815. }
  32816. return this._vertexBuffers;
  32817. };
  32818. /**
  32819. * Gets a boolean indicating if specific vertex buffer is present
  32820. * @param kind defines the data kind (Position, normal, etc...)
  32821. * @returns true if data is present
  32822. */
  32823. Geometry.prototype.isVerticesDataPresent = function (kind) {
  32824. if (!this._vertexBuffers) {
  32825. if (this._delayInfo) {
  32826. return this._delayInfo.indexOf(kind) !== -1;
  32827. }
  32828. return false;
  32829. }
  32830. return this._vertexBuffers[kind] !== undefined;
  32831. };
  32832. /**
  32833. * Gets a list of all attached data kinds (Position, normal, etc...)
  32834. * @returns a list of string containing all kinds
  32835. */
  32836. Geometry.prototype.getVerticesDataKinds = function () {
  32837. var result = [];
  32838. var kind;
  32839. if (!this._vertexBuffers && this._delayInfo) {
  32840. for (kind in this._delayInfo) {
  32841. result.push(kind);
  32842. }
  32843. }
  32844. else {
  32845. for (kind in this._vertexBuffers) {
  32846. result.push(kind);
  32847. }
  32848. }
  32849. return result;
  32850. };
  32851. /**
  32852. * Update index buffer
  32853. * @param indices defines the indices to store in the index buffer
  32854. * @param offset defines the offset in the target buffer where to store the data
  32855. */
  32856. Geometry.prototype.updateIndices = function (indices, offset) {
  32857. if (!this._indexBuffer) {
  32858. return;
  32859. }
  32860. if (!this._indexBufferIsUpdatable) {
  32861. this.setIndices(indices, null, true);
  32862. }
  32863. else {
  32864. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  32865. }
  32866. };
  32867. /**
  32868. * Creates a new index buffer
  32869. * @param indices defines the indices to store in the index buffer
  32870. * @param totalVertices defines the total number of vertices (could be null)
  32871. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  32872. */
  32873. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  32874. if (totalVertices === void 0) { totalVertices = null; }
  32875. if (updatable === void 0) { updatable = false; }
  32876. if (this._indexBuffer) {
  32877. this._engine._releaseBuffer(this._indexBuffer);
  32878. }
  32879. this._disposeVertexArrayObjects();
  32880. this._indices = indices;
  32881. this._indexBufferIsUpdatable = updatable;
  32882. if (this._meshes.length !== 0 && this._indices) {
  32883. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  32884. }
  32885. if (totalVertices != undefined) {
  32886. this._totalVertices = totalVertices;
  32887. }
  32888. var meshes = this._meshes;
  32889. var numOfMeshes = meshes.length;
  32890. for (var index = 0; index < numOfMeshes; index++) {
  32891. meshes[index]._createGlobalSubMesh(true);
  32892. }
  32893. this.notifyUpdate();
  32894. };
  32895. /**
  32896. * Return the total number of indices
  32897. * @returns the total number of indices
  32898. */
  32899. Geometry.prototype.getTotalIndices = function () {
  32900. if (!this.isReady()) {
  32901. return 0;
  32902. }
  32903. return this._indices.length;
  32904. };
  32905. /**
  32906. * Gets the index buffer array
  32907. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  32908. * @returns the index buffer array
  32909. */
  32910. Geometry.prototype.getIndices = function (copyWhenShared) {
  32911. if (!this.isReady()) {
  32912. return null;
  32913. }
  32914. var orig = this._indices;
  32915. if (!copyWhenShared || this._meshes.length === 1) {
  32916. return orig;
  32917. }
  32918. else {
  32919. var len = orig.length;
  32920. var copy = [];
  32921. for (var i = 0; i < len; i++) {
  32922. copy.push(orig[i]);
  32923. }
  32924. return copy;
  32925. }
  32926. };
  32927. /**
  32928. * Gets the index buffer
  32929. * @return the index buffer
  32930. */
  32931. Geometry.prototype.getIndexBuffer = function () {
  32932. if (!this.isReady()) {
  32933. return null;
  32934. }
  32935. return this._indexBuffer;
  32936. };
  32937. /** @ignore */
  32938. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  32939. if (effect === void 0) { effect = null; }
  32940. if (!effect || !this._vertexArrayObjects) {
  32941. return;
  32942. }
  32943. if (this._vertexArrayObjects[effect.key]) {
  32944. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  32945. delete this._vertexArrayObjects[effect.key];
  32946. }
  32947. };
  32948. /**
  32949. * Release the associated resources for a specific mesh
  32950. * @param mesh defines the source mesh
  32951. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  32952. */
  32953. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  32954. var meshes = this._meshes;
  32955. var index = meshes.indexOf(mesh);
  32956. if (index === -1) {
  32957. return;
  32958. }
  32959. meshes.splice(index, 1);
  32960. mesh._geometry = null;
  32961. if (meshes.length === 0 && shouldDispose) {
  32962. this.dispose();
  32963. }
  32964. };
  32965. /**
  32966. * Apply current geometry to a given mesh
  32967. * @param mesh defines the mesh to apply geometry to
  32968. */
  32969. Geometry.prototype.applyToMesh = function (mesh) {
  32970. if (mesh._geometry === this) {
  32971. return;
  32972. }
  32973. var previousGeometry = mesh._geometry;
  32974. if (previousGeometry) {
  32975. previousGeometry.releaseForMesh(mesh);
  32976. }
  32977. var meshes = this._meshes;
  32978. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  32979. mesh._geometry = this;
  32980. this._scene.pushGeometry(this);
  32981. meshes.push(mesh);
  32982. if (this.isReady()) {
  32983. this._applyToMesh(mesh);
  32984. }
  32985. else {
  32986. mesh._boundingInfo = this._boundingInfo;
  32987. }
  32988. };
  32989. Geometry.prototype.updateExtend = function (data, stride) {
  32990. if (data === void 0) { data = null; }
  32991. if (!data) {
  32992. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  32993. }
  32994. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  32995. };
  32996. Geometry.prototype._applyToMesh = function (mesh) {
  32997. var numOfMeshes = this._meshes.length;
  32998. // vertexBuffers
  32999. for (var kind in this._vertexBuffers) {
  33000. if (numOfMeshes === 1) {
  33001. this._vertexBuffers[kind].create();
  33002. }
  33003. var buffer = this._vertexBuffers[kind].getBuffer();
  33004. if (buffer)
  33005. buffer.references = numOfMeshes;
  33006. if (kind === BABYLON.VertexBuffer.PositionKind) {
  33007. if (!this._extend) {
  33008. this.updateExtend(this._vertexBuffers[kind].getData());
  33009. }
  33010. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  33011. mesh._createGlobalSubMesh(false);
  33012. //bounding info was just created again, world matrix should be applied again.
  33013. mesh._updateBoundingInfo();
  33014. }
  33015. }
  33016. // indexBuffer
  33017. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  33018. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  33019. }
  33020. if (this._indexBuffer) {
  33021. this._indexBuffer.references = numOfMeshes;
  33022. }
  33023. };
  33024. Geometry.prototype.notifyUpdate = function (kind) {
  33025. if (this.onGeometryUpdated) {
  33026. this.onGeometryUpdated(this, kind);
  33027. }
  33028. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  33029. var mesh = _a[_i];
  33030. mesh._markSubMeshesAsAttributesDirty();
  33031. }
  33032. };
  33033. /**
  33034. * Load the geometry if it was flagged as delay loaded
  33035. * @param scene defines the hosting scene
  33036. * @param onLoaded defines a callback called when the geometry is loaded
  33037. */
  33038. Geometry.prototype.load = function (scene, onLoaded) {
  33039. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  33040. return;
  33041. }
  33042. if (this.isReady()) {
  33043. if (onLoaded) {
  33044. onLoaded();
  33045. }
  33046. return;
  33047. }
  33048. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  33049. this._queueLoad(scene, onLoaded);
  33050. };
  33051. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  33052. var _this = this;
  33053. if (!this.delayLoadingFile) {
  33054. return;
  33055. }
  33056. scene._addPendingData(this);
  33057. scene._loadFile(this.delayLoadingFile, function (data) {
  33058. if (!_this._delayLoadingFunction) {
  33059. return;
  33060. }
  33061. _this._delayLoadingFunction(JSON.parse(data), _this);
  33062. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  33063. _this._delayInfo = [];
  33064. scene._removePendingData(_this);
  33065. var meshes = _this._meshes;
  33066. var numOfMeshes = meshes.length;
  33067. for (var index = 0; index < numOfMeshes; index++) {
  33068. _this._applyToMesh(meshes[index]);
  33069. }
  33070. if (onLoaded) {
  33071. onLoaded();
  33072. }
  33073. }, undefined, true);
  33074. };
  33075. /**
  33076. * Invert the geometry to move from a right handed system to a left handed one.
  33077. */
  33078. Geometry.prototype.toLeftHanded = function () {
  33079. // Flip faces
  33080. var tIndices = this.getIndices(false);
  33081. if (tIndices != null && tIndices.length > 0) {
  33082. for (var i = 0; i < tIndices.length; i += 3) {
  33083. var tTemp = tIndices[i + 0];
  33084. tIndices[i + 0] = tIndices[i + 2];
  33085. tIndices[i + 2] = tTemp;
  33086. }
  33087. this.setIndices(tIndices);
  33088. }
  33089. // Negate position.z
  33090. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  33091. if (tPositions != null && tPositions.length > 0) {
  33092. for (var i = 0; i < tPositions.length; i += 3) {
  33093. tPositions[i + 2] = -tPositions[i + 2];
  33094. }
  33095. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  33096. }
  33097. // Negate normal.z
  33098. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  33099. if (tNormals != null && tNormals.length > 0) {
  33100. for (var i = 0; i < tNormals.length; i += 3) {
  33101. tNormals[i + 2] = -tNormals[i + 2];
  33102. }
  33103. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  33104. }
  33105. };
  33106. // Cache
  33107. /** @ignore */
  33108. Geometry.prototype._resetPointsArrayCache = function () {
  33109. this._positions = null;
  33110. };
  33111. /** @ignore */
  33112. Geometry.prototype._generatePointsArray = function () {
  33113. if (this._positions)
  33114. return true;
  33115. this._positions = [];
  33116. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33117. if (!data) {
  33118. return false;
  33119. }
  33120. for (var index = 0; index < data.length; index += 3) {
  33121. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  33122. }
  33123. return true;
  33124. };
  33125. /**
  33126. * Gets a value indicating if the geometry is disposed
  33127. * @returns true if the geometry was disposed
  33128. */
  33129. Geometry.prototype.isDisposed = function () {
  33130. return this._isDisposed;
  33131. };
  33132. Geometry.prototype._disposeVertexArrayObjects = function () {
  33133. if (this._vertexArrayObjects) {
  33134. for (var kind in this._vertexArrayObjects) {
  33135. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  33136. }
  33137. this._vertexArrayObjects = {};
  33138. }
  33139. };
  33140. /**
  33141. * Free all associated resources
  33142. */
  33143. Geometry.prototype.dispose = function () {
  33144. var meshes = this._meshes;
  33145. var numOfMeshes = meshes.length;
  33146. var index;
  33147. for (index = 0; index < numOfMeshes; index++) {
  33148. this.releaseForMesh(meshes[index]);
  33149. }
  33150. this._meshes = [];
  33151. this._disposeVertexArrayObjects();
  33152. for (var kind in this._vertexBuffers) {
  33153. this._vertexBuffers[kind].dispose();
  33154. }
  33155. this._vertexBuffers = {};
  33156. this._totalVertices = 0;
  33157. if (this._indexBuffer) {
  33158. this._engine._releaseBuffer(this._indexBuffer);
  33159. }
  33160. this._indexBuffer = null;
  33161. this._indices = [];
  33162. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  33163. this.delayLoadingFile = null;
  33164. this._delayLoadingFunction = null;
  33165. this._delayInfo = [];
  33166. this._boundingInfo = null;
  33167. this._scene.removeGeometry(this);
  33168. this._isDisposed = true;
  33169. };
  33170. /**
  33171. * Clone the current geometry into a new geometry
  33172. * @param id defines the unique ID of the new geometry
  33173. * @returns a new geometry object
  33174. */
  33175. Geometry.prototype.copy = function (id) {
  33176. var vertexData = new BABYLON.VertexData();
  33177. vertexData.indices = [];
  33178. var indices = this.getIndices();
  33179. if (indices) {
  33180. for (var index = 0; index < indices.length; index++) {
  33181. vertexData.indices.push(indices[index]);
  33182. }
  33183. }
  33184. var updatable = false;
  33185. var stopChecking = false;
  33186. var kind;
  33187. for (kind in this._vertexBuffers) {
  33188. // using slice() to make a copy of the array and not just reference it
  33189. var data = this.getVerticesData(kind);
  33190. if (data instanceof Float32Array) {
  33191. vertexData.set(new Float32Array(data), kind);
  33192. }
  33193. else {
  33194. vertexData.set(data.slice(0), kind);
  33195. }
  33196. if (!stopChecking) {
  33197. var vb = this.getVertexBuffer(kind);
  33198. if (vb) {
  33199. updatable = vb.isUpdatable();
  33200. stopChecking = !updatable;
  33201. }
  33202. }
  33203. }
  33204. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  33205. geometry.delayLoadState = this.delayLoadState;
  33206. geometry.delayLoadingFile = this.delayLoadingFile;
  33207. geometry._delayLoadingFunction = this._delayLoadingFunction;
  33208. for (kind in this._delayInfo) {
  33209. geometry._delayInfo = geometry._delayInfo || [];
  33210. geometry._delayInfo.push(kind);
  33211. }
  33212. // Bounding info
  33213. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  33214. return geometry;
  33215. };
  33216. /**
  33217. * Serialize the current geometry info (and not the vertices data) into a JSON object
  33218. * @return a JSON representation of the current geometry data (without the vertices data)
  33219. */
  33220. Geometry.prototype.serialize = function () {
  33221. var serializationObject = {};
  33222. serializationObject.id = this.id;
  33223. serializationObject.updatable = this._updatable;
  33224. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  33225. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33226. }
  33227. return serializationObject;
  33228. };
  33229. Geometry.prototype.toNumberArray = function (origin) {
  33230. if (Array.isArray(origin)) {
  33231. return origin;
  33232. }
  33233. else {
  33234. return Array.prototype.slice.call(origin);
  33235. }
  33236. };
  33237. /**
  33238. * Serialize all vertices data into a JSON oject
  33239. * @returns a JSON representation of the current geometry data
  33240. */
  33241. Geometry.prototype.serializeVerticeData = function () {
  33242. var serializationObject = this.serialize();
  33243. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33244. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  33245. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33246. serializationObject.positions._updatable = true;
  33247. }
  33248. }
  33249. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33250. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  33251. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33252. serializationObject.normals._updatable = true;
  33253. }
  33254. }
  33255. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  33256. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  33257. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  33258. serializationObject.tangets._updatable = true;
  33259. }
  33260. }
  33261. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33262. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  33263. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  33264. serializationObject.uvs._updatable = true;
  33265. }
  33266. }
  33267. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33268. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  33269. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  33270. serializationObject.uv2s._updatable = true;
  33271. }
  33272. }
  33273. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  33274. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  33275. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  33276. serializationObject.uv3s._updatable = true;
  33277. }
  33278. }
  33279. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  33280. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  33281. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  33282. serializationObject.uv4s._updatable = true;
  33283. }
  33284. }
  33285. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  33286. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  33287. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  33288. serializationObject.uv5s._updatable = true;
  33289. }
  33290. }
  33291. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  33292. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  33293. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  33294. serializationObject.uv6s._updatable = true;
  33295. }
  33296. }
  33297. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  33298. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  33299. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  33300. serializationObject.colors._updatable = true;
  33301. }
  33302. }
  33303. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33304. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  33305. serializationObject.matricesIndices._isExpanded = true;
  33306. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33307. serializationObject.matricesIndices._updatable = true;
  33308. }
  33309. }
  33310. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33311. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  33312. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33313. serializationObject.matricesWeights._updatable = true;
  33314. }
  33315. }
  33316. serializationObject.indices = this.toNumberArray(this.getIndices());
  33317. return serializationObject;
  33318. };
  33319. // Statics
  33320. /**
  33321. * Extracts a clone of a mesh geometry
  33322. * @param mesh defines the source mesh
  33323. * @param id defines the unique ID of the new geometry object
  33324. * @returns the new geometry object
  33325. */
  33326. Geometry.ExtractFromMesh = function (mesh, id) {
  33327. var geometry = mesh._geometry;
  33328. if (!geometry) {
  33329. return null;
  33330. }
  33331. return geometry.copy(id);
  33332. };
  33333. /**
  33334. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  33335. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  33336. * Be aware Math.random() could cause collisions, but:
  33337. * "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"
  33338. * @returns a string containing a new GUID
  33339. */
  33340. Geometry.RandomId = function () {
  33341. return BABYLON.Tools.RandomId();
  33342. };
  33343. /** @ignore */
  33344. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  33345. var scene = mesh.getScene();
  33346. // Geometry
  33347. var geometryId = parsedGeometry.geometryId;
  33348. if (geometryId) {
  33349. var geometry = scene.getGeometryByID(geometryId);
  33350. if (geometry) {
  33351. geometry.applyToMesh(mesh);
  33352. }
  33353. }
  33354. else if (parsedGeometry instanceof ArrayBuffer) {
  33355. var binaryInfo = mesh._binaryInfo;
  33356. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  33357. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  33358. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  33359. }
  33360. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  33361. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  33362. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  33363. }
  33364. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  33365. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  33366. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  33367. }
  33368. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  33369. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  33370. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  33371. }
  33372. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  33373. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  33374. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  33375. }
  33376. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  33377. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  33378. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  33379. }
  33380. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  33381. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  33382. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  33383. }
  33384. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  33385. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  33386. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  33387. }
  33388. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  33389. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  33390. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  33391. }
  33392. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  33393. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  33394. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  33395. }
  33396. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  33397. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  33398. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  33399. }
  33400. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  33401. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  33402. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  33403. }
  33404. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  33405. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  33406. mesh.setIndices(indicesData, null);
  33407. }
  33408. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  33409. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  33410. mesh.subMeshes = [];
  33411. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  33412. var materialIndex = subMeshesData[(i * 5) + 0];
  33413. var verticesStart = subMeshesData[(i * 5) + 1];
  33414. var verticesCount = subMeshesData[(i * 5) + 2];
  33415. var indexStart = subMeshesData[(i * 5) + 3];
  33416. var indexCount = subMeshesData[(i * 5) + 4];
  33417. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  33418. }
  33419. }
  33420. }
  33421. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  33422. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  33423. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  33424. if (parsedGeometry.tangents) {
  33425. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  33426. }
  33427. if (parsedGeometry.uvs) {
  33428. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  33429. }
  33430. if (parsedGeometry.uvs2) {
  33431. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  33432. }
  33433. if (parsedGeometry.uvs3) {
  33434. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  33435. }
  33436. if (parsedGeometry.uvs4) {
  33437. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  33438. }
  33439. if (parsedGeometry.uvs5) {
  33440. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  33441. }
  33442. if (parsedGeometry.uvs6) {
  33443. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  33444. }
  33445. if (parsedGeometry.colors) {
  33446. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  33447. }
  33448. if (parsedGeometry.matricesIndices) {
  33449. if (!parsedGeometry.matricesIndices._isExpanded) {
  33450. var floatIndices = [];
  33451. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  33452. var matricesIndex = parsedGeometry.matricesIndices[i];
  33453. floatIndices.push(matricesIndex & 0x000000FF);
  33454. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  33455. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  33456. floatIndices.push(matricesIndex >> 24);
  33457. }
  33458. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  33459. }
  33460. else {
  33461. delete parsedGeometry.matricesIndices._isExpanded;
  33462. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  33463. }
  33464. }
  33465. if (parsedGeometry.matricesIndicesExtra) {
  33466. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  33467. var floatIndices = [];
  33468. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  33469. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  33470. floatIndices.push(matricesIndex & 0x000000FF);
  33471. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  33472. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  33473. floatIndices.push(matricesIndex >> 24);
  33474. }
  33475. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  33476. }
  33477. else {
  33478. delete parsedGeometry.matricesIndices._isExpanded;
  33479. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  33480. }
  33481. }
  33482. if (parsedGeometry.matricesWeights) {
  33483. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  33484. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  33485. }
  33486. if (parsedGeometry.matricesWeightsExtra) {
  33487. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  33488. }
  33489. mesh.setIndices(parsedGeometry.indices, null);
  33490. }
  33491. // SubMeshes
  33492. if (parsedGeometry.subMeshes) {
  33493. mesh.subMeshes = [];
  33494. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  33495. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  33496. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  33497. }
  33498. }
  33499. // Flat shading
  33500. if (mesh._shouldGenerateFlatShading) {
  33501. mesh.convertToFlatShadedMesh();
  33502. delete mesh._shouldGenerateFlatShading;
  33503. }
  33504. // Update
  33505. mesh.computeWorldMatrix(true);
  33506. // Octree
  33507. var sceneOctree = scene.selectionOctree;
  33508. if (sceneOctree !== undefined && sceneOctree !== null) {
  33509. sceneOctree.addMesh(mesh);
  33510. }
  33511. };
  33512. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  33513. var epsilon = 1e-3;
  33514. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  33515. return;
  33516. }
  33517. var noInfluenceBoneIndex = 0.0;
  33518. if (parsedGeometry.skeletonId > -1) {
  33519. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  33520. if (!skeleton) {
  33521. return;
  33522. }
  33523. noInfluenceBoneIndex = skeleton.bones.length;
  33524. }
  33525. else {
  33526. return;
  33527. }
  33528. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33529. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  33530. var matricesWeights = parsedGeometry.matricesWeights;
  33531. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  33532. var influencers = parsedGeometry.numBoneInfluencer;
  33533. var size = matricesWeights.length;
  33534. for (var i = 0; i < size; i += 4) {
  33535. var weight = 0.0;
  33536. var firstZeroWeight = -1;
  33537. for (var j = 0; j < 4; j++) {
  33538. var w = matricesWeights[i + j];
  33539. weight += w;
  33540. if (w < epsilon && firstZeroWeight < 0) {
  33541. firstZeroWeight = j;
  33542. }
  33543. }
  33544. if (matricesWeightsExtra) {
  33545. for (var j = 0; j < 4; j++) {
  33546. var w = matricesWeightsExtra[i + j];
  33547. weight += w;
  33548. if (w < epsilon && firstZeroWeight < 0) {
  33549. firstZeroWeight = j + 4;
  33550. }
  33551. }
  33552. }
  33553. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  33554. firstZeroWeight = influencers - 1;
  33555. }
  33556. if (weight > epsilon) {
  33557. var mweight = 1.0 / weight;
  33558. for (var j = 0; j < 4; j++) {
  33559. matricesWeights[i + j] *= mweight;
  33560. }
  33561. if (matricesWeightsExtra) {
  33562. for (var j = 0; j < 4; j++) {
  33563. matricesWeightsExtra[i + j] *= mweight;
  33564. }
  33565. }
  33566. }
  33567. else {
  33568. if (firstZeroWeight >= 4) {
  33569. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  33570. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  33571. }
  33572. else {
  33573. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  33574. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  33575. }
  33576. }
  33577. }
  33578. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  33579. if (parsedGeometry.matricesWeightsExtra) {
  33580. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  33581. }
  33582. };
  33583. /**
  33584. * Create a new geometry from persisted data (Using .babylon file format)
  33585. * @param parsedVertexData defines the persisted data
  33586. * @param scene defines the hosting scene
  33587. * @param rootUrl defines the root url to use to load assets (like delayed data)
  33588. * @returns the new geometry object
  33589. */
  33590. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  33591. if (scene.getGeometryByID(parsedVertexData.id)) {
  33592. return null; // null since geometry could be something else than a box...
  33593. }
  33594. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  33595. if (BABYLON.Tags) {
  33596. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  33597. }
  33598. if (parsedVertexData.delayLoadingFile) {
  33599. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33600. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  33601. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  33602. geometry._delayInfo = [];
  33603. if (parsedVertexData.hasUVs) {
  33604. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33605. }
  33606. if (parsedVertexData.hasUVs2) {
  33607. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33608. }
  33609. if (parsedVertexData.hasUVs3) {
  33610. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33611. }
  33612. if (parsedVertexData.hasUVs4) {
  33613. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33614. }
  33615. if (parsedVertexData.hasUVs5) {
  33616. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33617. }
  33618. if (parsedVertexData.hasUVs6) {
  33619. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33620. }
  33621. if (parsedVertexData.hasColors) {
  33622. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33623. }
  33624. if (parsedVertexData.hasMatricesIndices) {
  33625. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33626. }
  33627. if (parsedVertexData.hasMatricesWeights) {
  33628. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33629. }
  33630. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  33631. }
  33632. else {
  33633. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  33634. }
  33635. scene.pushGeometry(geometry, true);
  33636. return geometry;
  33637. };
  33638. return Geometry;
  33639. }());
  33640. BABYLON.Geometry = Geometry;
  33641. // Primitives
  33642. /// Abstract class
  33643. /**
  33644. * Abstract class used to provide common services for all typed geometries
  33645. */
  33646. var _PrimitiveGeometry = /** @class */ (function (_super) {
  33647. __extends(_PrimitiveGeometry, _super);
  33648. /**
  33649. * Creates a new typed geometry
  33650. * @param id defines the unique ID of the geometry
  33651. * @param scene defines the hosting scene
  33652. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33653. * @param mesh defines the hosting mesh (can be null)
  33654. */
  33655. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  33656. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  33657. if (mesh === void 0) { mesh = null; }
  33658. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  33659. _this._canBeRegenerated = _canBeRegenerated;
  33660. _this._beingRegenerated = true;
  33661. _this.regenerate();
  33662. _this._beingRegenerated = false;
  33663. return _this;
  33664. }
  33665. /**
  33666. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  33667. * @returns true if the geometry can be regenerated
  33668. */
  33669. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  33670. return this._canBeRegenerated;
  33671. };
  33672. /**
  33673. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  33674. */
  33675. _PrimitiveGeometry.prototype.regenerate = function () {
  33676. if (!this._canBeRegenerated) {
  33677. return;
  33678. }
  33679. this._beingRegenerated = true;
  33680. this.setAllVerticesData(this._regenerateVertexData(), false);
  33681. this._beingRegenerated = false;
  33682. };
  33683. /**
  33684. * Clone the geometry
  33685. * @param id defines the unique ID of the new geometry
  33686. * @returns the new geometry
  33687. */
  33688. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  33689. return _super.prototype.copy.call(this, id);
  33690. };
  33691. // overrides
  33692. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  33693. if (!this._beingRegenerated) {
  33694. return;
  33695. }
  33696. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  33697. };
  33698. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  33699. if (!this._beingRegenerated) {
  33700. return;
  33701. }
  33702. _super.prototype.setVerticesData.call(this, kind, data, false);
  33703. };
  33704. // to override
  33705. /** @ignore */
  33706. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  33707. throw new Error("Abstract method");
  33708. };
  33709. _PrimitiveGeometry.prototype.copy = function (id) {
  33710. throw new Error("Must be overriden in sub-classes.");
  33711. };
  33712. _PrimitiveGeometry.prototype.serialize = function () {
  33713. var serializationObject = _super.prototype.serialize.call(this);
  33714. serializationObject.canBeRegenerated = this.canBeRegenerated();
  33715. return serializationObject;
  33716. };
  33717. return _PrimitiveGeometry;
  33718. }(Geometry));
  33719. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  33720. /**
  33721. * Creates a ribbon geometry
  33722. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  33723. */
  33724. var RibbonGeometry = /** @class */ (function (_super) {
  33725. __extends(RibbonGeometry, _super);
  33726. /**
  33727. * Creates a ribbon geometry
  33728. * @param id defines the unique ID of the geometry
  33729. * @param scene defines the hosting scene
  33730. * @param pathArray defines the array of paths to use
  33731. * @param closeArray defines if the last path and the first path must be joined
  33732. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  33733. * @param offset defines the offset between points
  33734. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33735. * @param mesh defines the hosting mesh (can be null)
  33736. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33737. */
  33738. function RibbonGeometry(id, scene,
  33739. /**
  33740. * Defines the array of paths to use
  33741. */
  33742. pathArray,
  33743. /**
  33744. * Defines if the last and first points of each path in your pathArray must be joined
  33745. */
  33746. closeArray,
  33747. /**
  33748. * Defines if the last and first points of each path in your pathArray must be joined
  33749. */
  33750. closePath,
  33751. /**
  33752. * Defines the offset between points
  33753. */
  33754. offset, canBeRegenerated, mesh,
  33755. /**
  33756. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33757. */
  33758. side) {
  33759. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33760. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33761. _this.pathArray = pathArray;
  33762. _this.closeArray = closeArray;
  33763. _this.closePath = closePath;
  33764. _this.offset = offset;
  33765. _this.side = side;
  33766. return _this;
  33767. }
  33768. /** @ignore */
  33769. RibbonGeometry.prototype._regenerateVertexData = function () {
  33770. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  33771. };
  33772. RibbonGeometry.prototype.copy = function (id) {
  33773. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  33774. };
  33775. return RibbonGeometry;
  33776. }(_PrimitiveGeometry));
  33777. BABYLON.RibbonGeometry = RibbonGeometry;
  33778. /**
  33779. * Creates a box geometry
  33780. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  33781. */
  33782. var BoxGeometry = /** @class */ (function (_super) {
  33783. __extends(BoxGeometry, _super);
  33784. /**
  33785. * Creates a box geometry
  33786. * @param id defines the unique ID of the geometry
  33787. * @param scene defines the hosting scene
  33788. * @param size defines the zise of the box (width, height and depth are the same)
  33789. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33790. * @param mesh defines the hosting mesh (can be null)
  33791. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33792. */
  33793. function BoxGeometry(id, scene,
  33794. /**
  33795. * Defines the zise of the box (width, height and depth are the same)
  33796. */
  33797. size, canBeRegenerated, mesh,
  33798. /**
  33799. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33800. */
  33801. side) {
  33802. if (mesh === void 0) { mesh = null; }
  33803. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33804. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33805. _this.size = size;
  33806. _this.side = side;
  33807. return _this;
  33808. }
  33809. BoxGeometry.prototype._regenerateVertexData = function () {
  33810. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  33811. };
  33812. BoxGeometry.prototype.copy = function (id) {
  33813. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  33814. };
  33815. BoxGeometry.prototype.serialize = function () {
  33816. var serializationObject = _super.prototype.serialize.call(this);
  33817. serializationObject.size = this.size;
  33818. return serializationObject;
  33819. };
  33820. BoxGeometry.Parse = function (parsedBox, scene) {
  33821. if (scene.getGeometryByID(parsedBox.id)) {
  33822. return null; // null since geometry could be something else than a box...
  33823. }
  33824. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  33825. if (BABYLON.Tags) {
  33826. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  33827. }
  33828. scene.pushGeometry(box, true);
  33829. return box;
  33830. };
  33831. return BoxGeometry;
  33832. }(_PrimitiveGeometry));
  33833. BABYLON.BoxGeometry = BoxGeometry;
  33834. /**
  33835. * Creates a sphere geometry
  33836. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  33837. */
  33838. var SphereGeometry = /** @class */ (function (_super) {
  33839. __extends(SphereGeometry, _super);
  33840. /**
  33841. * Create a new sphere geometry
  33842. * @param id defines the unique ID of the geometry
  33843. * @param scene defines the hosting scene
  33844. * @param segments defines the number of segments to use to create the sphere
  33845. * @param diameter defines the diameter of the sphere
  33846. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33847. * @param mesh defines the hosting mesh (can be null)
  33848. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33849. */
  33850. function SphereGeometry(id, scene,
  33851. /**
  33852. * Defines the number of segments to use to create the sphere
  33853. */
  33854. segments,
  33855. /**
  33856. * Defines the diameter of the sphere
  33857. */
  33858. diameter, canBeRegenerated, mesh,
  33859. /**
  33860. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33861. */
  33862. side) {
  33863. if (mesh === void 0) { mesh = null; }
  33864. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33865. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33866. _this.segments = segments;
  33867. _this.diameter = diameter;
  33868. _this.side = side;
  33869. return _this;
  33870. }
  33871. SphereGeometry.prototype._regenerateVertexData = function () {
  33872. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  33873. };
  33874. SphereGeometry.prototype.copy = function (id) {
  33875. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  33876. };
  33877. SphereGeometry.prototype.serialize = function () {
  33878. var serializationObject = _super.prototype.serialize.call(this);
  33879. serializationObject.segments = this.segments;
  33880. serializationObject.diameter = this.diameter;
  33881. return serializationObject;
  33882. };
  33883. SphereGeometry.Parse = function (parsedSphere, scene) {
  33884. if (scene.getGeometryByID(parsedSphere.id)) {
  33885. return null; // null since geometry could be something else than a sphere...
  33886. }
  33887. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  33888. if (BABYLON.Tags) {
  33889. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  33890. }
  33891. scene.pushGeometry(sphere, true);
  33892. return sphere;
  33893. };
  33894. return SphereGeometry;
  33895. }(_PrimitiveGeometry));
  33896. BABYLON.SphereGeometry = SphereGeometry;
  33897. /**
  33898. * Creates a disc geometry
  33899. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  33900. */
  33901. var DiscGeometry = /** @class */ (function (_super) {
  33902. __extends(DiscGeometry, _super);
  33903. /**
  33904. * Creates a new disc geometry
  33905. * @param id defines the unique ID of the geometry
  33906. * @param scene defines the hosting scene
  33907. * @param radius defines the radius of the disc
  33908. * @param tessellation defines the tesselation factor to apply to the disc
  33909. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33910. * @param mesh defines the hosting mesh (can be null)
  33911. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33912. */
  33913. function DiscGeometry(id, scene,
  33914. /**
  33915. * Defines the radius of the disc
  33916. */
  33917. radius,
  33918. /**
  33919. * Defines the tesselation factor to apply to the disc
  33920. */
  33921. tessellation, canBeRegenerated, mesh,
  33922. /**
  33923. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33924. */
  33925. side) {
  33926. if (mesh === void 0) { mesh = null; }
  33927. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33928. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33929. _this.radius = radius;
  33930. _this.tessellation = tessellation;
  33931. _this.side = side;
  33932. return _this;
  33933. }
  33934. DiscGeometry.prototype._regenerateVertexData = function () {
  33935. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  33936. };
  33937. DiscGeometry.prototype.copy = function (id) {
  33938. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  33939. };
  33940. return DiscGeometry;
  33941. }(_PrimitiveGeometry));
  33942. BABYLON.DiscGeometry = DiscGeometry;
  33943. /**
  33944. * Creates a new cylinder geometry
  33945. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  33946. */
  33947. var CylinderGeometry = /** @class */ (function (_super) {
  33948. __extends(CylinderGeometry, _super);
  33949. /**
  33950. * Creates a new cylinder geometry
  33951. * @param id defines the unique ID of the geometry
  33952. * @param scene defines the hosting scene
  33953. * @param height defines the height of the cylinder
  33954. * @param diameterTop defines the diameter of the cylinder's top cap
  33955. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  33956. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  33957. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  33958. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33959. * @param mesh defines the hosting mesh (can be null)
  33960. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33961. */
  33962. function CylinderGeometry(id, scene,
  33963. /**
  33964. * Defines the height of the cylinder
  33965. */
  33966. height,
  33967. /**
  33968. * Defines the diameter of the cylinder's top cap
  33969. */
  33970. diameterTop,
  33971. /**
  33972. * Defines the diameter of the cylinder's bottom cap
  33973. */
  33974. diameterBottom,
  33975. /**
  33976. * Defines the tessellation factor to apply to the cylinder
  33977. */
  33978. tessellation,
  33979. /**
  33980. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  33981. */
  33982. subdivisions, canBeRegenerated, mesh,
  33983. /**
  33984. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33985. */
  33986. side) {
  33987. if (subdivisions === void 0) { subdivisions = 1; }
  33988. if (mesh === void 0) { mesh = null; }
  33989. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33990. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33991. _this.height = height;
  33992. _this.diameterTop = diameterTop;
  33993. _this.diameterBottom = diameterBottom;
  33994. _this.tessellation = tessellation;
  33995. _this.subdivisions = subdivisions;
  33996. _this.side = side;
  33997. return _this;
  33998. }
  33999. CylinderGeometry.prototype._regenerateVertexData = function () {
  34000. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  34001. };
  34002. CylinderGeometry.prototype.copy = function (id) {
  34003. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  34004. };
  34005. CylinderGeometry.prototype.serialize = function () {
  34006. var serializationObject = _super.prototype.serialize.call(this);
  34007. serializationObject.height = this.height;
  34008. serializationObject.diameterTop = this.diameterTop;
  34009. serializationObject.diameterBottom = this.diameterBottom;
  34010. serializationObject.tessellation = this.tessellation;
  34011. return serializationObject;
  34012. };
  34013. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  34014. if (scene.getGeometryByID(parsedCylinder.id)) {
  34015. return null; // null since geometry could be something else than a cylinder...
  34016. }
  34017. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  34018. if (BABYLON.Tags) {
  34019. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  34020. }
  34021. scene.pushGeometry(cylinder, true);
  34022. return cylinder;
  34023. };
  34024. return CylinderGeometry;
  34025. }(_PrimitiveGeometry));
  34026. BABYLON.CylinderGeometry = CylinderGeometry;
  34027. /**
  34028. * Creates a new torus geometry
  34029. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  34030. */
  34031. var TorusGeometry = /** @class */ (function (_super) {
  34032. __extends(TorusGeometry, _super);
  34033. /**
  34034. * Creates a new torus geometry
  34035. * @param id defines the unique ID of the geometry
  34036. * @param scene defines the hosting scene
  34037. * @param diameter defines the diameter of the torus
  34038. * @param thickness defines the thickness of the torus (ie. internal diameter)
  34039. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  34040. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34041. * @param mesh defines the hosting mesh (can be null)
  34042. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34043. */
  34044. function TorusGeometry(id, scene,
  34045. /**
  34046. * Defines the diameter of the torus
  34047. */
  34048. diameter,
  34049. /**
  34050. * Defines the thickness of the torus (ie. internal diameter)
  34051. */
  34052. thickness,
  34053. /**
  34054. * Defines the tesselation factor to apply to the torus
  34055. */
  34056. tessellation, canBeRegenerated, mesh,
  34057. /**
  34058. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34059. */
  34060. side) {
  34061. if (mesh === void 0) { mesh = null; }
  34062. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34063. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34064. _this.diameter = diameter;
  34065. _this.thickness = thickness;
  34066. _this.tessellation = tessellation;
  34067. _this.side = side;
  34068. return _this;
  34069. }
  34070. TorusGeometry.prototype._regenerateVertexData = function () {
  34071. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  34072. };
  34073. TorusGeometry.prototype.copy = function (id) {
  34074. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  34075. };
  34076. TorusGeometry.prototype.serialize = function () {
  34077. var serializationObject = _super.prototype.serialize.call(this);
  34078. serializationObject.diameter = this.diameter;
  34079. serializationObject.thickness = this.thickness;
  34080. serializationObject.tessellation = this.tessellation;
  34081. return serializationObject;
  34082. };
  34083. TorusGeometry.Parse = function (parsedTorus, scene) {
  34084. if (scene.getGeometryByID(parsedTorus.id)) {
  34085. return null; // null since geometry could be something else than a torus...
  34086. }
  34087. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  34088. if (BABYLON.Tags) {
  34089. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  34090. }
  34091. scene.pushGeometry(torus, true);
  34092. return torus;
  34093. };
  34094. return TorusGeometry;
  34095. }(_PrimitiveGeometry));
  34096. BABYLON.TorusGeometry = TorusGeometry;
  34097. /**
  34098. * Creates a new ground geometry
  34099. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  34100. */
  34101. var GroundGeometry = /** @class */ (function (_super) {
  34102. __extends(GroundGeometry, _super);
  34103. /**
  34104. * Creates a new ground geometry
  34105. * @param id defines the unique ID of the geometry
  34106. * @param scene defines the hosting scene
  34107. * @param width defines the width of the ground
  34108. * @param height defines the height of the ground
  34109. * @param subdivisions defines the subdivisions to apply to the ground
  34110. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34111. * @param mesh defines the hosting mesh (can be null)
  34112. */
  34113. function GroundGeometry(id, scene,
  34114. /**
  34115. * Defines the width of the ground
  34116. */
  34117. width,
  34118. /**
  34119. * Defines the height of the ground
  34120. */
  34121. height,
  34122. /**
  34123. * Defines the subdivisions to apply to the ground
  34124. */
  34125. subdivisions, canBeRegenerated, mesh) {
  34126. if (mesh === void 0) { mesh = null; }
  34127. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34128. _this.width = width;
  34129. _this.height = height;
  34130. _this.subdivisions = subdivisions;
  34131. return _this;
  34132. }
  34133. GroundGeometry.prototype._regenerateVertexData = function () {
  34134. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  34135. };
  34136. GroundGeometry.prototype.copy = function (id) {
  34137. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  34138. };
  34139. GroundGeometry.prototype.serialize = function () {
  34140. var serializationObject = _super.prototype.serialize.call(this);
  34141. serializationObject.width = this.width;
  34142. serializationObject.height = this.height;
  34143. serializationObject.subdivisions = this.subdivisions;
  34144. return serializationObject;
  34145. };
  34146. GroundGeometry.Parse = function (parsedGround, scene) {
  34147. if (scene.getGeometryByID(parsedGround.id)) {
  34148. return null; // null since geometry could be something else than a ground...
  34149. }
  34150. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  34151. if (BABYLON.Tags) {
  34152. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  34153. }
  34154. scene.pushGeometry(ground, true);
  34155. return ground;
  34156. };
  34157. return GroundGeometry;
  34158. }(_PrimitiveGeometry));
  34159. BABYLON.GroundGeometry = GroundGeometry;
  34160. /**
  34161. * Creates a tiled ground geometry
  34162. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  34163. */
  34164. var TiledGroundGeometry = /** @class */ (function (_super) {
  34165. __extends(TiledGroundGeometry, _super);
  34166. /**
  34167. * Creates a tiled ground geometry
  34168. * @param id defines the unique ID of the geometry
  34169. * @param scene defines the hosting scene
  34170. * @param xmin defines the minimum value on X axis
  34171. * @param zmin defines the minimum value on Z axis
  34172. * @param xmax defines the maximum value on X axis
  34173. * @param zmax defines the maximum value on Z axis
  34174. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  34175. * @param precision defines the precision to use when computing the tiles
  34176. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34177. * @param mesh defines the hosting mesh (can be null)
  34178. */
  34179. function TiledGroundGeometry(id, scene,
  34180. /**
  34181. * Defines the minimum value on X axis
  34182. */
  34183. xmin,
  34184. /**
  34185. * Defines the minimum value on Z axis
  34186. */
  34187. zmin,
  34188. /**
  34189. * Defines the maximum value on X axis
  34190. */
  34191. xmax,
  34192. /**
  34193. * Defines the maximum value on Z axis
  34194. */
  34195. zmax,
  34196. /**
  34197. * Defines the subdivisions to apply to the ground
  34198. */
  34199. subdivisions,
  34200. /**
  34201. * Defines the precision to use when computing the tiles
  34202. */
  34203. precision, canBeRegenerated, mesh) {
  34204. if (mesh === void 0) { mesh = null; }
  34205. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34206. _this.xmin = xmin;
  34207. _this.zmin = zmin;
  34208. _this.xmax = xmax;
  34209. _this.zmax = zmax;
  34210. _this.subdivisions = subdivisions;
  34211. _this.precision = precision;
  34212. return _this;
  34213. }
  34214. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  34215. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  34216. };
  34217. TiledGroundGeometry.prototype.copy = function (id) {
  34218. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  34219. };
  34220. return TiledGroundGeometry;
  34221. }(_PrimitiveGeometry));
  34222. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  34223. /**
  34224. * Creates a plane geometry
  34225. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  34226. */
  34227. var PlaneGeometry = /** @class */ (function (_super) {
  34228. __extends(PlaneGeometry, _super);
  34229. /**
  34230. * Creates a plane geometry
  34231. * @param id defines the unique ID of the geometry
  34232. * @param scene defines the hosting scene
  34233. * @param size defines the size of the plane (width === height)
  34234. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34235. * @param mesh defines the hosting mesh (can be null)
  34236. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34237. */
  34238. function PlaneGeometry(id, scene,
  34239. /**
  34240. * Defines the size of the plane (width === height)
  34241. */
  34242. size, canBeRegenerated, mesh,
  34243. /**
  34244. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34245. */
  34246. side) {
  34247. if (mesh === void 0) { mesh = null; }
  34248. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34249. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34250. _this.size = size;
  34251. _this.side = side;
  34252. return _this;
  34253. }
  34254. PlaneGeometry.prototype._regenerateVertexData = function () {
  34255. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  34256. };
  34257. PlaneGeometry.prototype.copy = function (id) {
  34258. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  34259. };
  34260. PlaneGeometry.prototype.serialize = function () {
  34261. var serializationObject = _super.prototype.serialize.call(this);
  34262. serializationObject.size = this.size;
  34263. return serializationObject;
  34264. };
  34265. PlaneGeometry.Parse = function (parsedPlane, scene) {
  34266. if (scene.getGeometryByID(parsedPlane.id)) {
  34267. return null; // null since geometry could be something else than a ground...
  34268. }
  34269. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  34270. if (BABYLON.Tags) {
  34271. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  34272. }
  34273. scene.pushGeometry(plane, true);
  34274. return plane;
  34275. };
  34276. return PlaneGeometry;
  34277. }(_PrimitiveGeometry));
  34278. BABYLON.PlaneGeometry = PlaneGeometry;
  34279. /**
  34280. * Creates a torus knot geometry
  34281. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  34282. */
  34283. var TorusKnotGeometry = /** @class */ (function (_super) {
  34284. __extends(TorusKnotGeometry, _super);
  34285. /**
  34286. * Creates a torus knot geometry
  34287. * @param id defines the unique ID of the geometry
  34288. * @param scene defines the hosting scene
  34289. * @param radius defines the radius of the torus knot
  34290. * @param tube defines the thickness of the torus knot tube
  34291. * @param radialSegments defines the number of radial segments
  34292. * @param tubularSegments defines the number of tubular segments
  34293. * @param p defines the first number of windings
  34294. * @param q defines the second number of windings
  34295. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34296. * @param mesh defines the hosting mesh (can be null)
  34297. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34298. */
  34299. function TorusKnotGeometry(id, scene,
  34300. /**
  34301. * Defines the radius of the torus knot
  34302. */
  34303. radius,
  34304. /**
  34305. * Defines the thickness of the torus knot tube
  34306. */
  34307. tube,
  34308. /**
  34309. * Defines the number of radial segments
  34310. */
  34311. radialSegments,
  34312. /**
  34313. * Defines the number of tubular segments
  34314. */
  34315. tubularSegments,
  34316. /**
  34317. * Defines the first number of windings
  34318. */
  34319. p,
  34320. /**
  34321. * Defines the second number of windings
  34322. */
  34323. q, canBeRegenerated, mesh,
  34324. /**
  34325. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34326. */
  34327. side) {
  34328. if (mesh === void 0) { mesh = null; }
  34329. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34330. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34331. _this.radius = radius;
  34332. _this.tube = tube;
  34333. _this.radialSegments = radialSegments;
  34334. _this.tubularSegments = tubularSegments;
  34335. _this.p = p;
  34336. _this.q = q;
  34337. _this.side = side;
  34338. return _this;
  34339. }
  34340. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  34341. 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 });
  34342. };
  34343. TorusKnotGeometry.prototype.copy = function (id) {
  34344. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  34345. };
  34346. TorusKnotGeometry.prototype.serialize = function () {
  34347. var serializationObject = _super.prototype.serialize.call(this);
  34348. serializationObject.radius = this.radius;
  34349. serializationObject.tube = this.tube;
  34350. serializationObject.radialSegments = this.radialSegments;
  34351. serializationObject.tubularSegments = this.tubularSegments;
  34352. serializationObject.p = this.p;
  34353. serializationObject.q = this.q;
  34354. return serializationObject;
  34355. };
  34356. ;
  34357. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  34358. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  34359. return null; // null since geometry could be something else than a ground...
  34360. }
  34361. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  34362. if (BABYLON.Tags) {
  34363. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  34364. }
  34365. scene.pushGeometry(torusKnot, true);
  34366. return torusKnot;
  34367. };
  34368. return TorusKnotGeometry;
  34369. }(_PrimitiveGeometry));
  34370. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  34371. //}
  34372. })(BABYLON || (BABYLON = {}));
  34373. //# sourceMappingURL=babylon.geometry.js.map
  34374. var BABYLON;
  34375. (function (BABYLON) {
  34376. var PostProcessManager = /** @class */ (function () {
  34377. function PostProcessManager(scene) {
  34378. this._vertexBuffers = {};
  34379. this._scene = scene;
  34380. }
  34381. PostProcessManager.prototype._prepareBuffers = function () {
  34382. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  34383. return;
  34384. }
  34385. // VBO
  34386. var vertices = [];
  34387. vertices.push(1, 1);
  34388. vertices.push(-1, 1);
  34389. vertices.push(-1, -1);
  34390. vertices.push(1, -1);
  34391. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  34392. this._buildIndexBuffer();
  34393. };
  34394. PostProcessManager.prototype._buildIndexBuffer = function () {
  34395. // Indices
  34396. var indices = [];
  34397. indices.push(0);
  34398. indices.push(1);
  34399. indices.push(2);
  34400. indices.push(0);
  34401. indices.push(2);
  34402. indices.push(3);
  34403. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  34404. };
  34405. PostProcessManager.prototype._rebuild = function () {
  34406. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  34407. if (!vb) {
  34408. return;
  34409. }
  34410. vb._rebuild();
  34411. this._buildIndexBuffer();
  34412. };
  34413. // Methods
  34414. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  34415. if (sourceTexture === void 0) { sourceTexture = null; }
  34416. if (postProcesses === void 0) { postProcesses = null; }
  34417. var camera = this._scene.activeCamera;
  34418. if (!camera) {
  34419. return false;
  34420. }
  34421. var postProcesses = postProcesses || camera._postProcesses;
  34422. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  34423. return false;
  34424. }
  34425. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  34426. return true;
  34427. };
  34428. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  34429. if (targetTexture === void 0) { targetTexture = null; }
  34430. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  34431. var engine = this._scene.getEngine();
  34432. for (var index = 0; index < postProcesses.length; index++) {
  34433. if (index < postProcesses.length - 1) {
  34434. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  34435. }
  34436. else {
  34437. if (targetTexture) {
  34438. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  34439. }
  34440. else {
  34441. engine.restoreDefaultFramebuffer();
  34442. }
  34443. }
  34444. var pp = postProcesses[index];
  34445. var effect = pp.apply();
  34446. if (effect) {
  34447. pp.onBeforeRenderObservable.notifyObservers(effect);
  34448. // VBOs
  34449. this._prepareBuffers();
  34450. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  34451. // Draw order
  34452. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  34453. pp.onAfterRenderObservable.notifyObservers(effect);
  34454. }
  34455. }
  34456. // Restore depth buffer
  34457. engine.setDepthBuffer(true);
  34458. engine.setDepthWrite(true);
  34459. };
  34460. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  34461. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  34462. var camera = this._scene.activeCamera;
  34463. if (!camera) {
  34464. return;
  34465. }
  34466. postProcesses = postProcesses || camera._postProcesses;
  34467. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  34468. return;
  34469. }
  34470. var engine = this._scene.getEngine();
  34471. for (var index = 0, len = postProcesses.length; index < len; index++) {
  34472. if (index < len - 1) {
  34473. postProcesses[index + 1].activate(camera, targetTexture);
  34474. }
  34475. else {
  34476. if (targetTexture) {
  34477. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  34478. }
  34479. else {
  34480. engine.restoreDefaultFramebuffer();
  34481. }
  34482. }
  34483. if (doNotPresent) {
  34484. break;
  34485. }
  34486. var pp = postProcesses[index];
  34487. var effect = pp.apply();
  34488. if (effect) {
  34489. pp.onBeforeRenderObservable.notifyObservers(effect);
  34490. // VBOs
  34491. this._prepareBuffers();
  34492. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  34493. // Draw order
  34494. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  34495. pp.onAfterRenderObservable.notifyObservers(effect);
  34496. }
  34497. }
  34498. // Restore states
  34499. engine.setDepthBuffer(true);
  34500. engine.setDepthWrite(true);
  34501. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  34502. };
  34503. PostProcessManager.prototype.dispose = function () {
  34504. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  34505. if (buffer) {
  34506. buffer.dispose();
  34507. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  34508. }
  34509. if (this._indexBuffer) {
  34510. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  34511. this._indexBuffer = null;
  34512. }
  34513. };
  34514. return PostProcessManager;
  34515. }());
  34516. BABYLON.PostProcessManager = PostProcessManager;
  34517. })(BABYLON || (BABYLON = {}));
  34518. //# sourceMappingURL=babylon.postProcessManager.js.map
  34519. var BABYLON;
  34520. (function (BABYLON) {
  34521. /**
  34522. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  34523. */
  34524. var PerformanceMonitor = /** @class */ (function () {
  34525. /**
  34526. * constructor
  34527. * @param frameSampleSize The number of samples required to saturate the sliding window
  34528. */
  34529. function PerformanceMonitor(frameSampleSize) {
  34530. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  34531. this._enabled = true;
  34532. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  34533. }
  34534. /**
  34535. * Samples current frame
  34536. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  34537. */
  34538. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  34539. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  34540. if (!this._enabled)
  34541. return;
  34542. if (this._lastFrameTimeMs != null) {
  34543. var dt = timeMs - this._lastFrameTimeMs;
  34544. this._rollingFrameTime.add(dt);
  34545. }
  34546. this._lastFrameTimeMs = timeMs;
  34547. };
  34548. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  34549. /**
  34550. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  34551. * @return Average frame time in milliseconds
  34552. */
  34553. get: function () {
  34554. return this._rollingFrameTime.average;
  34555. },
  34556. enumerable: true,
  34557. configurable: true
  34558. });
  34559. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  34560. /**
  34561. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  34562. * @return Frame time variance in milliseconds squared
  34563. */
  34564. get: function () {
  34565. return this._rollingFrameTime.variance;
  34566. },
  34567. enumerable: true,
  34568. configurable: true
  34569. });
  34570. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  34571. /**
  34572. * Returns the frame time of the most recent frame
  34573. * @return Frame time in milliseconds
  34574. */
  34575. get: function () {
  34576. return this._rollingFrameTime.history(0);
  34577. },
  34578. enumerable: true,
  34579. configurable: true
  34580. });
  34581. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  34582. /**
  34583. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  34584. * @return Framerate in frames per second
  34585. */
  34586. get: function () {
  34587. return 1000.0 / this._rollingFrameTime.average;
  34588. },
  34589. enumerable: true,
  34590. configurable: true
  34591. });
  34592. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  34593. /**
  34594. * Returns the average framerate in frames per second using the most recent frame time
  34595. * @return Framerate in frames per second
  34596. */
  34597. get: function () {
  34598. var history = this._rollingFrameTime.history(0);
  34599. if (history === 0) {
  34600. return 0;
  34601. }
  34602. return 1000.0 / history;
  34603. },
  34604. enumerable: true,
  34605. configurable: true
  34606. });
  34607. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  34608. /**
  34609. * Returns true if enough samples have been taken to completely fill the sliding window
  34610. * @return true if saturated
  34611. */
  34612. get: function () {
  34613. return this._rollingFrameTime.isSaturated();
  34614. },
  34615. enumerable: true,
  34616. configurable: true
  34617. });
  34618. /**
  34619. * Enables contributions to the sliding window sample set
  34620. */
  34621. PerformanceMonitor.prototype.enable = function () {
  34622. this._enabled = true;
  34623. };
  34624. /**
  34625. * Disables contributions to the sliding window sample set
  34626. * Samples will not be interpolated over the disabled period
  34627. */
  34628. PerformanceMonitor.prototype.disable = function () {
  34629. this._enabled = false;
  34630. //clear last sample to avoid interpolating over the disabled period when next enabled
  34631. this._lastFrameTimeMs = null;
  34632. };
  34633. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  34634. /**
  34635. * Returns true if sampling is enabled
  34636. * @return true if enabled
  34637. */
  34638. get: function () {
  34639. return this._enabled;
  34640. },
  34641. enumerable: true,
  34642. configurable: true
  34643. });
  34644. /**
  34645. * Resets performance monitor
  34646. */
  34647. PerformanceMonitor.prototype.reset = function () {
  34648. //clear last sample to avoid interpolating over the disabled period when next enabled
  34649. this._lastFrameTimeMs = null;
  34650. //wipe record
  34651. this._rollingFrameTime.reset();
  34652. };
  34653. return PerformanceMonitor;
  34654. }());
  34655. BABYLON.PerformanceMonitor = PerformanceMonitor;
  34656. /**
  34657. * RollingAverage
  34658. *
  34659. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  34660. */
  34661. var RollingAverage = /** @class */ (function () {
  34662. /**
  34663. * constructor
  34664. * @param length The number of samples required to saturate the sliding window
  34665. */
  34666. function RollingAverage(length) {
  34667. this._samples = new Array(length);
  34668. this.reset();
  34669. }
  34670. /**
  34671. * Adds a sample to the sample set
  34672. * @param v The sample value
  34673. */
  34674. RollingAverage.prototype.add = function (v) {
  34675. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  34676. var delta;
  34677. //we need to check if we've already wrapped round
  34678. if (this.isSaturated()) {
  34679. //remove bottom of stack from mean
  34680. var bottomValue = this._samples[this._pos];
  34681. delta = bottomValue - this.average;
  34682. this.average -= delta / (this._sampleCount - 1);
  34683. this._m2 -= delta * (bottomValue - this.average);
  34684. }
  34685. else {
  34686. this._sampleCount++;
  34687. }
  34688. //add new value to mean
  34689. delta = v - this.average;
  34690. this.average += delta / (this._sampleCount);
  34691. this._m2 += delta * (v - this.average);
  34692. //set the new variance
  34693. this.variance = this._m2 / (this._sampleCount - 1);
  34694. this._samples[this._pos] = v;
  34695. this._pos++;
  34696. this._pos %= this._samples.length; //positive wrap around
  34697. };
  34698. /**
  34699. * Returns previously added values or null if outside of history or outside the sliding window domain
  34700. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  34701. * @return Value previously recorded with add() or null if outside of range
  34702. */
  34703. RollingAverage.prototype.history = function (i) {
  34704. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  34705. return 0;
  34706. }
  34707. var i0 = this._wrapPosition(this._pos - 1.0);
  34708. return this._samples[this._wrapPosition(i0 - i)];
  34709. };
  34710. /**
  34711. * Returns true if enough samples have been taken to completely fill the sliding window
  34712. * @return true if sample-set saturated
  34713. */
  34714. RollingAverage.prototype.isSaturated = function () {
  34715. return this._sampleCount >= this._samples.length;
  34716. };
  34717. /**
  34718. * Resets the rolling average (equivalent to 0 samples taken so far)
  34719. */
  34720. RollingAverage.prototype.reset = function () {
  34721. this.average = 0;
  34722. this.variance = 0;
  34723. this._sampleCount = 0;
  34724. this._pos = 0;
  34725. this._m2 = 0;
  34726. };
  34727. /**
  34728. * Wraps a value around the sample range boundaries
  34729. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  34730. * @return Wrapped position in sample range
  34731. */
  34732. RollingAverage.prototype._wrapPosition = function (i) {
  34733. var max = this._samples.length;
  34734. return ((i % max) + max) % max;
  34735. };
  34736. return RollingAverage;
  34737. }());
  34738. BABYLON.RollingAverage = RollingAverage;
  34739. })(BABYLON || (BABYLON = {}));
  34740. //# sourceMappingURL=babylon.performanceMonitor.js.map
  34741. var BABYLON;
  34742. (function (BABYLON) {
  34743. /**
  34744. * This groups together the common properties used for image processing either in direct forward pass
  34745. * or through post processing effect depending on the use of the image processing pipeline in your scene
  34746. * or not.
  34747. */
  34748. var ImageProcessingConfiguration = /** @class */ (function () {
  34749. function ImageProcessingConfiguration() {
  34750. /**
  34751. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  34752. */
  34753. this.colorCurves = new BABYLON.ColorCurves();
  34754. this._colorCurvesEnabled = false;
  34755. this._colorGradingEnabled = false;
  34756. this._colorGradingWithGreenDepth = true;
  34757. this._colorGradingBGR = true;
  34758. this._exposure = 1.0;
  34759. this._toneMappingEnabled = false;
  34760. this._contrast = 1.0;
  34761. /**
  34762. * Vignette stretch size.
  34763. */
  34764. this.vignetteStretch = 0;
  34765. /**
  34766. * Vignette centre X Offset.
  34767. */
  34768. this.vignetteCentreX = 0;
  34769. /**
  34770. * Vignette centre Y Offset.
  34771. */
  34772. this.vignetteCentreY = 0;
  34773. /**
  34774. * Vignette weight or intensity of the vignette effect.
  34775. */
  34776. this.vignetteWeight = 1.5;
  34777. /**
  34778. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  34779. * if vignetteEnabled is set to true.
  34780. */
  34781. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  34782. /**
  34783. * Camera field of view used by the Vignette effect.
  34784. */
  34785. this.vignetteCameraFov = 0.5;
  34786. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  34787. this._vignetteEnabled = false;
  34788. this._applyByPostProcess = false;
  34789. this._isEnabled = true;
  34790. /**
  34791. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  34792. * @type {BABYLON.Observable}
  34793. */
  34794. this.onUpdateParameters = new BABYLON.Observable();
  34795. }
  34796. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  34797. /**
  34798. * Gets wether the color curves effect is enabled.
  34799. */
  34800. get: function () {
  34801. return this._colorCurvesEnabled;
  34802. },
  34803. /**
  34804. * Sets wether the color curves effect is enabled.
  34805. */
  34806. set: function (value) {
  34807. if (this._colorCurvesEnabled === value) {
  34808. return;
  34809. }
  34810. this._colorCurvesEnabled = value;
  34811. this._updateParameters();
  34812. },
  34813. enumerable: true,
  34814. configurable: true
  34815. });
  34816. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  34817. /**
  34818. * Gets wether the color grading effect is enabled.
  34819. */
  34820. get: function () {
  34821. return this._colorGradingEnabled;
  34822. },
  34823. /**
  34824. * Sets wether the color grading effect is enabled.
  34825. */
  34826. set: function (value) {
  34827. if (this._colorGradingEnabled === value) {
  34828. return;
  34829. }
  34830. this._colorGradingEnabled = value;
  34831. this._updateParameters();
  34832. },
  34833. enumerable: true,
  34834. configurable: true
  34835. });
  34836. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  34837. /**
  34838. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  34839. */
  34840. get: function () {
  34841. return this._colorGradingWithGreenDepth;
  34842. },
  34843. /**
  34844. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  34845. */
  34846. set: function (value) {
  34847. if (this._colorGradingWithGreenDepth === value) {
  34848. return;
  34849. }
  34850. this._colorGradingWithGreenDepth = value;
  34851. this._updateParameters();
  34852. },
  34853. enumerable: true,
  34854. configurable: true
  34855. });
  34856. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  34857. /**
  34858. * Gets wether the color grading texture contains BGR values.
  34859. */
  34860. get: function () {
  34861. return this._colorGradingBGR;
  34862. },
  34863. /**
  34864. * Sets wether the color grading texture contains BGR values.
  34865. */
  34866. set: function (value) {
  34867. if (this._colorGradingBGR === value) {
  34868. return;
  34869. }
  34870. this._colorGradingBGR = value;
  34871. this._updateParameters();
  34872. },
  34873. enumerable: true,
  34874. configurable: true
  34875. });
  34876. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  34877. /**
  34878. * Gets the Exposure used in the effect.
  34879. */
  34880. get: function () {
  34881. return this._exposure;
  34882. },
  34883. /**
  34884. * Sets the Exposure used in the effect.
  34885. */
  34886. set: function (value) {
  34887. if (this._exposure === value) {
  34888. return;
  34889. }
  34890. this._exposure = value;
  34891. this._updateParameters();
  34892. },
  34893. enumerable: true,
  34894. configurable: true
  34895. });
  34896. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  34897. /**
  34898. * Gets wether the tone mapping effect is enabled.
  34899. */
  34900. get: function () {
  34901. return this._toneMappingEnabled;
  34902. },
  34903. /**
  34904. * Sets wether the tone mapping effect is enabled.
  34905. */
  34906. set: function (value) {
  34907. if (this._toneMappingEnabled === value) {
  34908. return;
  34909. }
  34910. this._toneMappingEnabled = value;
  34911. this._updateParameters();
  34912. },
  34913. enumerable: true,
  34914. configurable: true
  34915. });
  34916. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  34917. /**
  34918. * Gets the contrast used in the effect.
  34919. */
  34920. get: function () {
  34921. return this._contrast;
  34922. },
  34923. /**
  34924. * Sets the contrast used in the effect.
  34925. */
  34926. set: function (value) {
  34927. if (this._contrast === value) {
  34928. return;
  34929. }
  34930. this._contrast = value;
  34931. this._updateParameters();
  34932. },
  34933. enumerable: true,
  34934. configurable: true
  34935. });
  34936. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  34937. /**
  34938. * Gets the vignette blend mode allowing different kind of effect.
  34939. */
  34940. get: function () {
  34941. return this._vignetteBlendMode;
  34942. },
  34943. /**
  34944. * Sets the vignette blend mode allowing different kind of effect.
  34945. */
  34946. set: function (value) {
  34947. if (this._vignetteBlendMode === value) {
  34948. return;
  34949. }
  34950. this._vignetteBlendMode = value;
  34951. this._updateParameters();
  34952. },
  34953. enumerable: true,
  34954. configurable: true
  34955. });
  34956. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  34957. /**
  34958. * Gets wether the vignette effect is enabled.
  34959. */
  34960. get: function () {
  34961. return this._vignetteEnabled;
  34962. },
  34963. /**
  34964. * Sets wether the vignette effect is enabled.
  34965. */
  34966. set: function (value) {
  34967. if (this._vignetteEnabled === value) {
  34968. return;
  34969. }
  34970. this._vignetteEnabled = value;
  34971. this._updateParameters();
  34972. },
  34973. enumerable: true,
  34974. configurable: true
  34975. });
  34976. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  34977. /**
  34978. * Gets wether the image processing is applied through a post process or not.
  34979. */
  34980. get: function () {
  34981. return this._applyByPostProcess;
  34982. },
  34983. /**
  34984. * Sets wether the image processing is applied through a post process or not.
  34985. */
  34986. set: function (value) {
  34987. if (this._applyByPostProcess === value) {
  34988. return;
  34989. }
  34990. this._applyByPostProcess = value;
  34991. this._updateParameters();
  34992. },
  34993. enumerable: true,
  34994. configurable: true
  34995. });
  34996. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  34997. /**
  34998. * Gets wether the image processing is enabled or not.
  34999. */
  35000. get: function () {
  35001. return this._isEnabled;
  35002. },
  35003. /**
  35004. * Sets wether the image processing is enabled or not.
  35005. */
  35006. set: function (value) {
  35007. if (this._isEnabled === value) {
  35008. return;
  35009. }
  35010. this._isEnabled = value;
  35011. this._updateParameters();
  35012. },
  35013. enumerable: true,
  35014. configurable: true
  35015. });
  35016. /**
  35017. * Method called each time the image processing information changes requires to recompile the effect.
  35018. */
  35019. ImageProcessingConfiguration.prototype._updateParameters = function () {
  35020. this.onUpdateParameters.notifyObservers(this);
  35021. };
  35022. ImageProcessingConfiguration.prototype.getClassName = function () {
  35023. return "ImageProcessingConfiguration";
  35024. };
  35025. /**
  35026. * Prepare the list of uniforms associated with the Image Processing effects.
  35027. * @param uniformsList The list of uniforms used in the effect
  35028. * @param defines the list of defines currently in use
  35029. */
  35030. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  35031. if (defines.EXPOSURE) {
  35032. uniforms.push("exposureLinear");
  35033. }
  35034. if (defines.CONTRAST) {
  35035. uniforms.push("contrast");
  35036. }
  35037. if (defines.COLORGRADING) {
  35038. uniforms.push("colorTransformSettings");
  35039. }
  35040. if (defines.VIGNETTE) {
  35041. uniforms.push("vInverseScreenSize");
  35042. uniforms.push("vignetteSettings1");
  35043. uniforms.push("vignetteSettings2");
  35044. }
  35045. if (defines.COLORCURVES) {
  35046. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  35047. }
  35048. };
  35049. /**
  35050. * Prepare the list of samplers associated with the Image Processing effects.
  35051. * @param uniformsList The list of uniforms used in the effect
  35052. * @param defines the list of defines currently in use
  35053. */
  35054. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  35055. if (defines.COLORGRADING) {
  35056. samplersList.push("txColorTransform");
  35057. }
  35058. };
  35059. /**
  35060. * Prepare the list of defines associated to the shader.
  35061. * @param defines the list of defines to complete
  35062. */
  35063. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  35064. if (forPostProcess === void 0) { forPostProcess = false; }
  35065. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  35066. defines.VIGNETTE = false;
  35067. defines.TONEMAPPING = false;
  35068. defines.CONTRAST = false;
  35069. defines.EXPOSURE = false;
  35070. defines.COLORCURVES = false;
  35071. defines.COLORGRADING = false;
  35072. defines.COLORGRADING3D = false;
  35073. defines.IMAGEPROCESSING = false;
  35074. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  35075. return;
  35076. }
  35077. defines.VIGNETTE = this.vignetteEnabled;
  35078. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  35079. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  35080. defines.TONEMAPPING = this.toneMappingEnabled;
  35081. defines.CONTRAST = (this.contrast !== 1.0);
  35082. defines.EXPOSURE = (this.exposure !== 1.0);
  35083. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  35084. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  35085. if (defines.COLORGRADING) {
  35086. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  35087. }
  35088. else {
  35089. defines.COLORGRADING3D = false;
  35090. }
  35091. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  35092. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  35093. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  35094. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  35095. };
  35096. /**
  35097. * Returns true if all the image processing information are ready.
  35098. */
  35099. ImageProcessingConfiguration.prototype.isReady = function () {
  35100. // Color Grading texure can not be none blocking.
  35101. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  35102. };
  35103. /**
  35104. * Binds the image processing to the shader.
  35105. * @param effect The effect to bind to
  35106. */
  35107. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  35108. if (aspectRatio === void 0) { aspectRatio = 1; }
  35109. // Color Curves
  35110. if (this._colorCurvesEnabled && this.colorCurves) {
  35111. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  35112. }
  35113. // Vignette
  35114. if (this._vignetteEnabled) {
  35115. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  35116. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  35117. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  35118. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  35119. var vignetteScaleX = vignetteScaleY * aspectRatio;
  35120. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  35121. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  35122. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  35123. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  35124. var vignettePower = -2.0 * this.vignetteWeight;
  35125. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  35126. }
  35127. // Exposure
  35128. effect.setFloat("exposureLinear", this.exposure);
  35129. // Contrast
  35130. effect.setFloat("contrast", this.contrast);
  35131. // Color transform settings
  35132. if (this.colorGradingTexture) {
  35133. effect.setTexture("txColorTransform", this.colorGradingTexture);
  35134. var textureSize = this.colorGradingTexture.getSize().height;
  35135. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  35136. 0.5 / textureSize, // textureOffset
  35137. textureSize, // textureSize
  35138. this.colorGradingTexture.level // weight
  35139. );
  35140. }
  35141. };
  35142. /**
  35143. * Clones the current image processing instance.
  35144. * @return The cloned image processing
  35145. */
  35146. ImageProcessingConfiguration.prototype.clone = function () {
  35147. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  35148. };
  35149. /**
  35150. * Serializes the current image processing instance to a json representation.
  35151. * @return a JSON representation
  35152. */
  35153. ImageProcessingConfiguration.prototype.serialize = function () {
  35154. return BABYLON.SerializationHelper.Serialize(this);
  35155. };
  35156. /**
  35157. * Parses the image processing from a json representation.
  35158. * @param source the JSON source to parse
  35159. * @return The parsed image processing
  35160. */
  35161. ImageProcessingConfiguration.Parse = function (source) {
  35162. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  35163. };
  35164. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  35165. /**
  35166. * Used to apply the vignette as a mix with the pixel color.
  35167. */
  35168. get: function () {
  35169. return this._VIGNETTEMODE_MULTIPLY;
  35170. },
  35171. enumerable: true,
  35172. configurable: true
  35173. });
  35174. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  35175. /**
  35176. * Used to apply the vignette as a replacement of the pixel color.
  35177. */
  35178. get: function () {
  35179. return this._VIGNETTEMODE_OPAQUE;
  35180. },
  35181. enumerable: true,
  35182. configurable: true
  35183. });
  35184. // Static constants associated to the image processing.
  35185. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  35186. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  35187. __decorate([
  35188. BABYLON.serializeAsColorCurves()
  35189. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  35190. __decorate([
  35191. BABYLON.serialize()
  35192. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  35193. __decorate([
  35194. BABYLON.serializeAsTexture()
  35195. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  35196. __decorate([
  35197. BABYLON.serialize()
  35198. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  35199. __decorate([
  35200. BABYLON.serialize()
  35201. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  35202. __decorate([
  35203. BABYLON.serialize()
  35204. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  35205. __decorate([
  35206. BABYLON.serialize()
  35207. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  35208. __decorate([
  35209. BABYLON.serialize()
  35210. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  35211. __decorate([
  35212. BABYLON.serialize()
  35213. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  35214. __decorate([
  35215. BABYLON.serialize()
  35216. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  35217. __decorate([
  35218. BABYLON.serialize()
  35219. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  35220. __decorate([
  35221. BABYLON.serialize()
  35222. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  35223. __decorate([
  35224. BABYLON.serialize()
  35225. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  35226. __decorate([
  35227. BABYLON.serializeAsColor4()
  35228. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  35229. __decorate([
  35230. BABYLON.serialize()
  35231. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  35232. __decorate([
  35233. BABYLON.serialize()
  35234. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  35235. __decorate([
  35236. BABYLON.serialize()
  35237. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  35238. __decorate([
  35239. BABYLON.serialize()
  35240. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  35241. __decorate([
  35242. BABYLON.serialize()
  35243. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  35244. return ImageProcessingConfiguration;
  35245. }());
  35246. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  35247. })(BABYLON || (BABYLON = {}));
  35248. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  35249. var BABYLON;
  35250. (function (BABYLON) {
  35251. /**
  35252. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  35253. * It can help converting any input color in a desired output one. This can then be used to create effects
  35254. * from sepia, black and white to sixties or futuristic rendering...
  35255. *
  35256. * The only supported format is currently 3dl.
  35257. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  35258. */
  35259. var ColorGradingTexture = /** @class */ (function (_super) {
  35260. __extends(ColorGradingTexture, _super);
  35261. /**
  35262. * Instantiates a ColorGradingTexture from the following parameters.
  35263. *
  35264. * @param url The location of the color gradind data (currently only supporting 3dl)
  35265. * @param scene The scene the texture will be used in
  35266. */
  35267. function ColorGradingTexture(url, scene) {
  35268. var _this = _super.call(this, scene) || this;
  35269. if (!url) {
  35270. return _this;
  35271. }
  35272. _this._engine = scene.getEngine();
  35273. _this._textureMatrix = BABYLON.Matrix.Identity();
  35274. _this.name = url;
  35275. _this.url = url;
  35276. _this.hasAlpha = false;
  35277. _this.isCube = false;
  35278. _this.is3D = _this._engine.webGLVersion > 1;
  35279. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35280. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35281. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35282. _this.anisotropicFilteringLevel = 1;
  35283. _this._texture = _this._getFromCache(url, true);
  35284. if (!_this._texture) {
  35285. if (!scene.useDelayedTextureLoading) {
  35286. _this.loadTexture();
  35287. }
  35288. else {
  35289. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  35290. }
  35291. }
  35292. return _this;
  35293. }
  35294. /**
  35295. * Returns the texture matrix used in most of the material.
  35296. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  35297. */
  35298. ColorGradingTexture.prototype.getTextureMatrix = function () {
  35299. return this._textureMatrix;
  35300. };
  35301. /**
  35302. * Occurs when the file being loaded is a .3dl LUT file.
  35303. */
  35304. ColorGradingTexture.prototype.load3dlTexture = function () {
  35305. var engine = this._engine;
  35306. var texture;
  35307. if (engine.webGLVersion === 1) {
  35308. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35309. }
  35310. else {
  35311. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35312. }
  35313. this._texture = texture;
  35314. var callback = function (text) {
  35315. if (typeof text !== "string") {
  35316. return;
  35317. }
  35318. var data = null;
  35319. var tempData = null;
  35320. var line;
  35321. var lines = text.split('\n');
  35322. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  35323. var maxColor = 0;
  35324. for (var i = 0; i < lines.length; i++) {
  35325. line = lines[i];
  35326. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  35327. continue;
  35328. if (line.indexOf('#') === 0)
  35329. continue;
  35330. var words = line.split(" ");
  35331. if (size === 0) {
  35332. // Number of space + one
  35333. size = words.length;
  35334. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  35335. tempData = new Float32Array(size * size * size * 4);
  35336. continue;
  35337. }
  35338. if (size != 0) {
  35339. var r = Math.max(parseInt(words[0]), 0);
  35340. var g = Math.max(parseInt(words[1]), 0);
  35341. var b = Math.max(parseInt(words[2]), 0);
  35342. maxColor = Math.max(r, maxColor);
  35343. maxColor = Math.max(g, maxColor);
  35344. maxColor = Math.max(b, maxColor);
  35345. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  35346. if (tempData) {
  35347. tempData[pixelStorageIndex + 0] = r;
  35348. tempData[pixelStorageIndex + 1] = g;
  35349. tempData[pixelStorageIndex + 2] = b;
  35350. }
  35351. pixelIndexSlice++;
  35352. if (pixelIndexSlice % size == 0) {
  35353. pixelIndexH++;
  35354. pixelIndexSlice = 0;
  35355. if (pixelIndexH % size == 0) {
  35356. pixelIndexW++;
  35357. pixelIndexH = 0;
  35358. }
  35359. }
  35360. }
  35361. }
  35362. if (tempData && data) {
  35363. for (var i = 0; i < tempData.length; i++) {
  35364. if (i > 0 && (i + 1) % 4 === 0) {
  35365. data[i] = 255;
  35366. }
  35367. else {
  35368. var value = tempData[i];
  35369. data[i] = (value / maxColor * 255);
  35370. }
  35371. }
  35372. }
  35373. if (texture.is3D) {
  35374. texture.updateSize(size, size, size);
  35375. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  35376. }
  35377. else {
  35378. texture.updateSize(size * size, size);
  35379. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  35380. }
  35381. };
  35382. var scene = this.getScene();
  35383. if (scene) {
  35384. scene._loadFile(this.url, callback);
  35385. }
  35386. else {
  35387. this._engine._loadFile(this.url, callback);
  35388. }
  35389. return this._texture;
  35390. };
  35391. /**
  35392. * Starts the loading process of the texture.
  35393. */
  35394. ColorGradingTexture.prototype.loadTexture = function () {
  35395. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  35396. this.load3dlTexture();
  35397. }
  35398. };
  35399. /**
  35400. * Clones the color gradind texture.
  35401. */
  35402. ColorGradingTexture.prototype.clone = function () {
  35403. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  35404. // Base texture
  35405. newTexture.level = this.level;
  35406. return newTexture;
  35407. };
  35408. /**
  35409. * Called during delayed load for textures.
  35410. */
  35411. ColorGradingTexture.prototype.delayLoad = function () {
  35412. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  35413. return;
  35414. }
  35415. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  35416. this._texture = this._getFromCache(this.url, true);
  35417. if (!this._texture) {
  35418. this.loadTexture();
  35419. }
  35420. };
  35421. /**
  35422. * Parses a color grading texture serialized by Babylon.
  35423. * @param parsedTexture The texture information being parsedTexture
  35424. * @param scene The scene to load the texture in
  35425. * @param rootUrl The root url of the data assets to load
  35426. * @return A color gradind texture
  35427. */
  35428. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  35429. var texture = null;
  35430. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  35431. texture = new ColorGradingTexture(parsedTexture.name, scene);
  35432. texture.name = parsedTexture.name;
  35433. texture.level = parsedTexture.level;
  35434. }
  35435. return texture;
  35436. };
  35437. /**
  35438. * Serializes the LUT texture to json format.
  35439. */
  35440. ColorGradingTexture.prototype.serialize = function () {
  35441. if (!this.name) {
  35442. return null;
  35443. }
  35444. var serializationObject = {};
  35445. serializationObject.name = this.name;
  35446. serializationObject.level = this.level;
  35447. serializationObject.customType = "BABYLON.ColorGradingTexture";
  35448. return serializationObject;
  35449. };
  35450. /**
  35451. * Empty line regex stored for GC.
  35452. */
  35453. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  35454. return ColorGradingTexture;
  35455. }(BABYLON.BaseTexture));
  35456. BABYLON.ColorGradingTexture = ColorGradingTexture;
  35457. })(BABYLON || (BABYLON = {}));
  35458. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  35459. var BABYLON;
  35460. (function (BABYLON) {
  35461. /**
  35462. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  35463. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  35464. * 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;
  35465. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  35466. */
  35467. var ColorCurves = /** @class */ (function () {
  35468. function ColorCurves() {
  35469. this._dirty = true;
  35470. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  35471. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  35472. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  35473. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  35474. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  35475. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  35476. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  35477. this._globalHue = 30;
  35478. this._globalDensity = 0;
  35479. this._globalSaturation = 0;
  35480. this._globalExposure = 0;
  35481. this._highlightsHue = 30;
  35482. this._highlightsDensity = 0;
  35483. this._highlightsSaturation = 0;
  35484. this._highlightsExposure = 0;
  35485. this._midtonesHue = 30;
  35486. this._midtonesDensity = 0;
  35487. this._midtonesSaturation = 0;
  35488. this._midtonesExposure = 0;
  35489. this._shadowsHue = 30;
  35490. this._shadowsDensity = 0;
  35491. this._shadowsSaturation = 0;
  35492. this._shadowsExposure = 0;
  35493. }
  35494. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  35495. /**
  35496. * Gets the global Hue value.
  35497. * 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).
  35498. */
  35499. get: function () {
  35500. return this._globalHue;
  35501. },
  35502. /**
  35503. * Sets the global Hue value.
  35504. * 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).
  35505. */
  35506. set: function (value) {
  35507. this._globalHue = value;
  35508. this._dirty = true;
  35509. },
  35510. enumerable: true,
  35511. configurable: true
  35512. });
  35513. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  35514. /**
  35515. * Gets the global Density value.
  35516. * 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.
  35517. * Values less than zero provide a filter of opposite hue.
  35518. */
  35519. get: function () {
  35520. return this._globalDensity;
  35521. },
  35522. /**
  35523. * Sets the global Density value.
  35524. * 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.
  35525. * Values less than zero provide a filter of opposite hue.
  35526. */
  35527. set: function (value) {
  35528. this._globalDensity = value;
  35529. this._dirty = true;
  35530. },
  35531. enumerable: true,
  35532. configurable: true
  35533. });
  35534. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  35535. /**
  35536. * Gets the global Saturation value.
  35537. * 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.
  35538. */
  35539. get: function () {
  35540. return this._globalSaturation;
  35541. },
  35542. /**
  35543. * Sets the global Saturation value.
  35544. * 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.
  35545. */
  35546. set: function (value) {
  35547. this._globalSaturation = value;
  35548. this._dirty = true;
  35549. },
  35550. enumerable: true,
  35551. configurable: true
  35552. });
  35553. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  35554. /**
  35555. * Gets the highlights Hue value.
  35556. * 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).
  35557. */
  35558. get: function () {
  35559. return this._highlightsHue;
  35560. },
  35561. /**
  35562. * Sets the highlights Hue value.
  35563. * 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).
  35564. */
  35565. set: function (value) {
  35566. this._highlightsHue = value;
  35567. this._dirty = true;
  35568. },
  35569. enumerable: true,
  35570. configurable: true
  35571. });
  35572. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  35573. /**
  35574. * Gets the highlights Density value.
  35575. * 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.
  35576. * Values less than zero provide a filter of opposite hue.
  35577. */
  35578. get: function () {
  35579. return this._highlightsDensity;
  35580. },
  35581. /**
  35582. * Sets the highlights Density value.
  35583. * 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.
  35584. * Values less than zero provide a filter of opposite hue.
  35585. */
  35586. set: function (value) {
  35587. this._highlightsDensity = value;
  35588. this._dirty = true;
  35589. },
  35590. enumerable: true,
  35591. configurable: true
  35592. });
  35593. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  35594. /**
  35595. * Gets the highlights Saturation value.
  35596. * 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.
  35597. */
  35598. get: function () {
  35599. return this._highlightsSaturation;
  35600. },
  35601. /**
  35602. * Sets the highlights Saturation value.
  35603. * 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.
  35604. */
  35605. set: function (value) {
  35606. this._highlightsSaturation = value;
  35607. this._dirty = true;
  35608. },
  35609. enumerable: true,
  35610. configurable: true
  35611. });
  35612. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  35613. /**
  35614. * Gets the highlights Exposure value.
  35615. * 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.
  35616. */
  35617. get: function () {
  35618. return this._highlightsExposure;
  35619. },
  35620. /**
  35621. * Sets the highlights Exposure value.
  35622. * 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.
  35623. */
  35624. set: function (value) {
  35625. this._highlightsExposure = value;
  35626. this._dirty = true;
  35627. },
  35628. enumerable: true,
  35629. configurable: true
  35630. });
  35631. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  35632. /**
  35633. * Gets the midtones Hue value.
  35634. * 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).
  35635. */
  35636. get: function () {
  35637. return this._midtonesHue;
  35638. },
  35639. /**
  35640. * Sets the midtones Hue value.
  35641. * 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).
  35642. */
  35643. set: function (value) {
  35644. this._midtonesHue = value;
  35645. this._dirty = true;
  35646. },
  35647. enumerable: true,
  35648. configurable: true
  35649. });
  35650. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  35651. /**
  35652. * Gets the midtones Density value.
  35653. * 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.
  35654. * Values less than zero provide a filter of opposite hue.
  35655. */
  35656. get: function () {
  35657. return this._midtonesDensity;
  35658. },
  35659. /**
  35660. * Sets the midtones Density value.
  35661. * 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.
  35662. * Values less than zero provide a filter of opposite hue.
  35663. */
  35664. set: function (value) {
  35665. this._midtonesDensity = value;
  35666. this._dirty = true;
  35667. },
  35668. enumerable: true,
  35669. configurable: true
  35670. });
  35671. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  35672. /**
  35673. * Gets the midtones Saturation value.
  35674. * 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.
  35675. */
  35676. get: function () {
  35677. return this._midtonesSaturation;
  35678. },
  35679. /**
  35680. * Sets the midtones Saturation value.
  35681. * 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.
  35682. */
  35683. set: function (value) {
  35684. this._midtonesSaturation = value;
  35685. this._dirty = true;
  35686. },
  35687. enumerable: true,
  35688. configurable: true
  35689. });
  35690. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  35691. /**
  35692. * Gets the midtones Exposure value.
  35693. * 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.
  35694. */
  35695. get: function () {
  35696. return this._midtonesExposure;
  35697. },
  35698. /**
  35699. * Sets the midtones Exposure value.
  35700. * 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.
  35701. */
  35702. set: function (value) {
  35703. this._midtonesExposure = value;
  35704. this._dirty = true;
  35705. },
  35706. enumerable: true,
  35707. configurable: true
  35708. });
  35709. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  35710. /**
  35711. * Gets the shadows Hue value.
  35712. * 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).
  35713. */
  35714. get: function () {
  35715. return this._shadowsHue;
  35716. },
  35717. /**
  35718. * Sets the shadows Hue value.
  35719. * 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).
  35720. */
  35721. set: function (value) {
  35722. this._shadowsHue = value;
  35723. this._dirty = true;
  35724. },
  35725. enumerable: true,
  35726. configurable: true
  35727. });
  35728. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  35729. /**
  35730. * Gets the shadows Density value.
  35731. * 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.
  35732. * Values less than zero provide a filter of opposite hue.
  35733. */
  35734. get: function () {
  35735. return this._shadowsDensity;
  35736. },
  35737. /**
  35738. * Sets the shadows Density value.
  35739. * 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.
  35740. * Values less than zero provide a filter of opposite hue.
  35741. */
  35742. set: function (value) {
  35743. this._shadowsDensity = value;
  35744. this._dirty = true;
  35745. },
  35746. enumerable: true,
  35747. configurable: true
  35748. });
  35749. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  35750. /**
  35751. * Gets the shadows Saturation value.
  35752. * 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.
  35753. */
  35754. get: function () {
  35755. return this._shadowsSaturation;
  35756. },
  35757. /**
  35758. * Sets the shadows Saturation value.
  35759. * 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.
  35760. */
  35761. set: function (value) {
  35762. this._shadowsSaturation = value;
  35763. this._dirty = true;
  35764. },
  35765. enumerable: true,
  35766. configurable: true
  35767. });
  35768. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  35769. /**
  35770. * Gets the shadows Exposure value.
  35771. * 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.
  35772. */
  35773. get: function () {
  35774. return this._shadowsExposure;
  35775. },
  35776. /**
  35777. * Sets the shadows Exposure value.
  35778. * 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.
  35779. */
  35780. set: function (value) {
  35781. this._shadowsExposure = value;
  35782. this._dirty = true;
  35783. },
  35784. enumerable: true,
  35785. configurable: true
  35786. });
  35787. ColorCurves.prototype.getClassName = function () {
  35788. return "ColorCurves";
  35789. };
  35790. /**
  35791. * Binds the color curves to the shader.
  35792. * @param colorCurves The color curve to bind
  35793. * @param effect The effect to bind to
  35794. */
  35795. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  35796. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  35797. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  35798. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  35799. if (colorCurves._dirty) {
  35800. colorCurves._dirty = false;
  35801. // Fill in global info.
  35802. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  35803. // Compute highlights info.
  35804. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  35805. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  35806. // Compute midtones info.
  35807. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  35808. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  35809. // Compute shadows info.
  35810. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  35811. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  35812. // Compute deltas (neutral is midtones).
  35813. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  35814. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  35815. }
  35816. if (effect) {
  35817. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  35818. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  35819. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  35820. }
  35821. };
  35822. /**
  35823. * Prepare the list of uniforms associated with the ColorCurves effects.
  35824. * @param uniformsList The list of uniforms used in the effect
  35825. */
  35826. ColorCurves.PrepareUniforms = function (uniformsList) {
  35827. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  35828. };
  35829. /**
  35830. * Returns color grading data based on a hue, density, saturation and exposure value.
  35831. * @param filterHue The hue of the color filter.
  35832. * @param filterDensity The density of the color filter.
  35833. * @param saturation The saturation.
  35834. * @param exposure The exposure.
  35835. * @param result The result data container.
  35836. */
  35837. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  35838. if (hue == null) {
  35839. return;
  35840. }
  35841. hue = ColorCurves.clamp(hue, 0, 360);
  35842. density = ColorCurves.clamp(density, -100, 100);
  35843. saturation = ColorCurves.clamp(saturation, -100, 100);
  35844. exposure = ColorCurves.clamp(exposure, -100, 100);
  35845. // Remap the slider/config filter density with non-linear mapping and also scale by half
  35846. // so that the maximum filter density is only 50% control. This provides fine control
  35847. // for small values and reasonable range.
  35848. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  35849. density *= 0.5;
  35850. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  35851. if (density < 0) {
  35852. density *= -1;
  35853. hue = (hue + 180) % 360;
  35854. }
  35855. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  35856. result.scaleToRef(2, result);
  35857. result.a = 1 + 0.01 * saturation;
  35858. };
  35859. /**
  35860. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  35861. * @param value The input slider value in range [-100,100].
  35862. * @returns Adjusted value.
  35863. */
  35864. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  35865. value /= 100;
  35866. var x = Math.abs(value);
  35867. x = Math.pow(x, 2);
  35868. if (value < 0) {
  35869. x *= -1;
  35870. }
  35871. x *= 100;
  35872. return x;
  35873. };
  35874. /**
  35875. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  35876. * @param hue The hue (H) input.
  35877. * @param saturation The saturation (S) input.
  35878. * @param brightness The brightness (B) input.
  35879. * @result An RGBA color represented as Vector4.
  35880. */
  35881. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  35882. var h = ColorCurves.clamp(hue, 0, 360);
  35883. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  35884. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  35885. if (s === 0) {
  35886. result.r = v;
  35887. result.g = v;
  35888. result.b = v;
  35889. }
  35890. else {
  35891. // sector 0 to 5
  35892. h /= 60;
  35893. var i = Math.floor(h);
  35894. // fractional part of h
  35895. var f = h - i;
  35896. var p = v * (1 - s);
  35897. var q = v * (1 - s * f);
  35898. var t = v * (1 - s * (1 - f));
  35899. switch (i) {
  35900. case 0:
  35901. result.r = v;
  35902. result.g = t;
  35903. result.b = p;
  35904. break;
  35905. case 1:
  35906. result.r = q;
  35907. result.g = v;
  35908. result.b = p;
  35909. break;
  35910. case 2:
  35911. result.r = p;
  35912. result.g = v;
  35913. result.b = t;
  35914. break;
  35915. case 3:
  35916. result.r = p;
  35917. result.g = q;
  35918. result.b = v;
  35919. break;
  35920. case 4:
  35921. result.r = t;
  35922. result.g = p;
  35923. result.b = v;
  35924. break;
  35925. default:// case 5:
  35926. result.r = v;
  35927. result.g = p;
  35928. result.b = q;
  35929. break;
  35930. }
  35931. }
  35932. result.a = 1;
  35933. };
  35934. /**
  35935. * Returns a value clamped between min and max
  35936. * @param value The value to clamp
  35937. * @param min The minimum of value
  35938. * @param max The maximum of value
  35939. * @returns The clamped value.
  35940. */
  35941. ColorCurves.clamp = function (value, min, max) {
  35942. return Math.min(Math.max(value, min), max);
  35943. };
  35944. /**
  35945. * Clones the current color curve instance.
  35946. * @return The cloned curves
  35947. */
  35948. ColorCurves.prototype.clone = function () {
  35949. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  35950. };
  35951. /**
  35952. * Serializes the current color curve instance to a json representation.
  35953. * @return a JSON representation
  35954. */
  35955. ColorCurves.prototype.serialize = function () {
  35956. return BABYLON.SerializationHelper.Serialize(this);
  35957. };
  35958. /**
  35959. * Parses the color curve from a json representation.
  35960. * @param source the JSON source to parse
  35961. * @return The parsed curves
  35962. */
  35963. ColorCurves.Parse = function (source) {
  35964. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  35965. };
  35966. __decorate([
  35967. BABYLON.serialize()
  35968. ], ColorCurves.prototype, "_globalHue", void 0);
  35969. __decorate([
  35970. BABYLON.serialize()
  35971. ], ColorCurves.prototype, "_globalDensity", void 0);
  35972. __decorate([
  35973. BABYLON.serialize()
  35974. ], ColorCurves.prototype, "_globalSaturation", void 0);
  35975. __decorate([
  35976. BABYLON.serialize()
  35977. ], ColorCurves.prototype, "_globalExposure", void 0);
  35978. __decorate([
  35979. BABYLON.serialize()
  35980. ], ColorCurves.prototype, "_highlightsHue", void 0);
  35981. __decorate([
  35982. BABYLON.serialize()
  35983. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  35984. __decorate([
  35985. BABYLON.serialize()
  35986. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  35987. __decorate([
  35988. BABYLON.serialize()
  35989. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  35990. __decorate([
  35991. BABYLON.serialize()
  35992. ], ColorCurves.prototype, "_midtonesHue", void 0);
  35993. __decorate([
  35994. BABYLON.serialize()
  35995. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  35996. __decorate([
  35997. BABYLON.serialize()
  35998. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  35999. __decorate([
  36000. BABYLON.serialize()
  36001. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  36002. return ColorCurves;
  36003. }());
  36004. BABYLON.ColorCurves = ColorCurves;
  36005. })(BABYLON || (BABYLON = {}));
  36006. //# sourceMappingURL=babylon.colorCurves.js.map
  36007. //# sourceMappingURL=babylon.behavior.js.map
  36008. var BABYLON;
  36009. (function (BABYLON) {
  36010. var MaterialHelper = /** @class */ (function () {
  36011. function MaterialHelper() {
  36012. }
  36013. MaterialHelper.BindEyePosition = function (effect, scene) {
  36014. if (scene._forcedViewPosition) {
  36015. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  36016. return;
  36017. }
  36018. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  36019. };
  36020. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  36021. defines._needUVs = true;
  36022. defines[key] = true;
  36023. if (texture.getTextureMatrix().isIdentity(true)) {
  36024. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  36025. if (texture.coordinatesIndex === 0) {
  36026. defines["MAINUV1"] = true;
  36027. }
  36028. else {
  36029. defines["MAINUV2"] = true;
  36030. }
  36031. }
  36032. else {
  36033. defines[key + "DIRECTUV"] = 0;
  36034. }
  36035. };
  36036. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  36037. var matrix = texture.getTextureMatrix();
  36038. if (!matrix.isIdentity(true)) {
  36039. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  36040. }
  36041. };
  36042. /**
  36043. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  36044. * @param mesh defines the current mesh
  36045. * @param scene defines the current scene
  36046. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  36047. * @param pointsCloud defines if point cloud rendering has to be turned on
  36048. * @param fogEnabled defines if fog has to be turned on
  36049. * @param alphaTest defines if alpha testing has to be turned on
  36050. * @param defines defines the current list of defines
  36051. */
  36052. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  36053. if (defines._areMiscDirty) {
  36054. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  36055. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  36056. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  36057. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  36058. defines["ALPHATEST"] = alphaTest;
  36059. }
  36060. };
  36061. /**
  36062. * Helper used to prepare the list of defines associated with frame values for shader compilation
  36063. * @param scene defines the current scene
  36064. * @param engine defines the current engine
  36065. * @param defines specifies the list of active defines
  36066. * @param useInstances defines if instances have to be turned on
  36067. * @param alphaTest defines if alpha testing has to be turned on
  36068. */
  36069. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances) {
  36070. var changed = false;
  36071. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  36072. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  36073. changed = true;
  36074. }
  36075. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  36076. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  36077. changed = true;
  36078. }
  36079. if (defines["INSTANCES"] !== useInstances) {
  36080. defines["INSTANCES"] = useInstances;
  36081. changed = true;
  36082. }
  36083. if (changed) {
  36084. defines.markAsUnprocessed();
  36085. }
  36086. };
  36087. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  36088. if (useMorphTargets === void 0) { useMorphTargets = false; }
  36089. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  36090. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  36091. return false;
  36092. }
  36093. defines._normals = defines._needNormals;
  36094. defines._uvs = defines._needUVs;
  36095. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  36096. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36097. defines["TANGENT"] = true;
  36098. }
  36099. if (defines._needUVs) {
  36100. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  36101. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  36102. }
  36103. else {
  36104. defines["UV1"] = false;
  36105. defines["UV2"] = false;
  36106. }
  36107. if (useVertexColor) {
  36108. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  36109. defines["VERTEXCOLOR"] = hasVertexColors;
  36110. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  36111. }
  36112. if (useBones) {
  36113. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  36114. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  36115. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  36116. }
  36117. else {
  36118. defines["NUM_BONE_INFLUENCERS"] = 0;
  36119. defines["BonesPerMesh"] = 0;
  36120. }
  36121. }
  36122. if (useMorphTargets) {
  36123. var manager = mesh.morphTargetManager;
  36124. if (manager) {
  36125. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  36126. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  36127. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  36128. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  36129. }
  36130. else {
  36131. defines["MORPHTARGETS_TANGENT"] = false;
  36132. defines["MORPHTARGETS_NORMAL"] = false;
  36133. defines["MORPHTARGETS"] = false;
  36134. defines["NUM_MORPH_INFLUENCERS"] = 0;
  36135. }
  36136. }
  36137. return true;
  36138. };
  36139. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  36140. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  36141. if (disableLighting === void 0) { disableLighting = false; }
  36142. if (!defines._areLightsDirty) {
  36143. return defines._needNormals;
  36144. }
  36145. var lightIndex = 0;
  36146. var needNormals = false;
  36147. var needRebuild = false;
  36148. var lightmapMode = false;
  36149. var shadowEnabled = false;
  36150. var specularEnabled = false;
  36151. if (scene.lightsEnabled && !disableLighting) {
  36152. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  36153. var light = _a[_i];
  36154. needNormals = true;
  36155. if (defines["LIGHT" + lightIndex] === undefined) {
  36156. needRebuild = true;
  36157. }
  36158. defines["LIGHT" + lightIndex] = true;
  36159. defines["SPOTLIGHT" + lightIndex] = false;
  36160. defines["HEMILIGHT" + lightIndex] = false;
  36161. defines["POINTLIGHT" + lightIndex] = false;
  36162. defines["DIRLIGHT" + lightIndex] = false;
  36163. var type;
  36164. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  36165. type = "SPOTLIGHT" + lightIndex;
  36166. }
  36167. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  36168. type = "HEMILIGHT" + lightIndex;
  36169. }
  36170. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  36171. type = "POINTLIGHT" + lightIndex;
  36172. }
  36173. else {
  36174. type = "DIRLIGHT" + lightIndex;
  36175. }
  36176. defines[type] = true;
  36177. // Specular
  36178. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  36179. specularEnabled = true;
  36180. }
  36181. // Shadows
  36182. defines["SHADOW" + lightIndex] = false;
  36183. defines["SHADOWPCF" + lightIndex] = false;
  36184. defines["SHADOWESM" + lightIndex] = false;
  36185. defines["SHADOWCUBE" + lightIndex] = false;
  36186. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  36187. var shadowGenerator = light.getShadowGenerator();
  36188. if (shadowGenerator) {
  36189. shadowEnabled = true;
  36190. shadowGenerator.prepareDefines(defines, lightIndex);
  36191. }
  36192. }
  36193. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  36194. lightmapMode = true;
  36195. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  36196. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  36197. }
  36198. else {
  36199. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  36200. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  36201. }
  36202. lightIndex++;
  36203. if (lightIndex === maxSimultaneousLights)
  36204. break;
  36205. }
  36206. }
  36207. defines["SPECULARTERM"] = specularEnabled;
  36208. defines["SHADOWS"] = shadowEnabled;
  36209. // Resetting all other lights if any
  36210. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  36211. if (defines["LIGHT" + index] !== undefined) {
  36212. defines["LIGHT" + index] = false;
  36213. defines["HEMILIGHT" + lightIndex] = false;
  36214. defines["POINTLIGHT" + lightIndex] = false;
  36215. defines["DIRLIGHT" + lightIndex] = false;
  36216. defines["SPOTLIGHT" + lightIndex] = false;
  36217. defines["SHADOW" + lightIndex] = false;
  36218. }
  36219. }
  36220. var caps = scene.getEngine().getCaps();
  36221. if (defines["SHADOWFLOAT"] === undefined) {
  36222. needRebuild = true;
  36223. }
  36224. defines["SHADOWFLOAT"] = shadowEnabled &&
  36225. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  36226. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  36227. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  36228. if (needRebuild) {
  36229. defines.rebuild();
  36230. }
  36231. return needNormals;
  36232. };
  36233. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  36234. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  36235. var uniformsList;
  36236. var uniformBuffersList = null;
  36237. if (uniformsListOrOptions.uniformsNames) {
  36238. var options = uniformsListOrOptions;
  36239. uniformsList = options.uniformsNames;
  36240. uniformBuffersList = options.uniformBuffersNames;
  36241. samplersList = options.samplers;
  36242. defines = options.defines;
  36243. maxSimultaneousLights = options.maxSimultaneousLights;
  36244. }
  36245. else {
  36246. uniformsList = uniformsListOrOptions;
  36247. if (!samplersList) {
  36248. samplersList = [];
  36249. }
  36250. }
  36251. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  36252. if (!defines["LIGHT" + lightIndex]) {
  36253. break;
  36254. }
  36255. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  36256. if (uniformBuffersList) {
  36257. uniformBuffersList.push("Light" + lightIndex);
  36258. }
  36259. samplersList.push("shadowSampler" + lightIndex);
  36260. }
  36261. if (defines["NUM_MORPH_INFLUENCERS"]) {
  36262. uniformsList.push("morphTargetInfluences");
  36263. }
  36264. };
  36265. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  36266. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  36267. if (rank === void 0) { rank = 0; }
  36268. var lightFallbackRank = 0;
  36269. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  36270. if (!defines["LIGHT" + lightIndex]) {
  36271. break;
  36272. }
  36273. if (lightIndex > 0) {
  36274. lightFallbackRank = rank + lightIndex;
  36275. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  36276. }
  36277. if (!defines["SHADOWS"]) {
  36278. if (defines["SHADOW" + lightIndex]) {
  36279. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  36280. }
  36281. if (defines["SHADOWPCF" + lightIndex]) {
  36282. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  36283. }
  36284. if (defines["SHADOWESM" + lightIndex]) {
  36285. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  36286. }
  36287. }
  36288. }
  36289. return lightFallbackRank++;
  36290. };
  36291. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  36292. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  36293. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  36294. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  36295. var manager = mesh.morphTargetManager;
  36296. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  36297. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  36298. for (var index = 0; index < influencers; index++) {
  36299. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  36300. if (normal) {
  36301. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  36302. }
  36303. if (tangent) {
  36304. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  36305. }
  36306. if (attribs.length > maxAttributesCount) {
  36307. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  36308. }
  36309. }
  36310. }
  36311. };
  36312. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  36313. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  36314. fallbacks.addCPUSkinningFallback(0, mesh);
  36315. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  36316. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  36317. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  36318. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  36319. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  36320. }
  36321. }
  36322. };
  36323. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  36324. if (defines["INSTANCES"]) {
  36325. attribs.push("world0");
  36326. attribs.push("world1");
  36327. attribs.push("world2");
  36328. attribs.push("world3");
  36329. }
  36330. };
  36331. // Bindings
  36332. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  36333. if (light.shadowEnabled && mesh.receiveShadows) {
  36334. var shadowGenerator = light.getShadowGenerator();
  36335. if (shadowGenerator) {
  36336. shadowGenerator.bindShadowLight(lightIndex, effect);
  36337. }
  36338. }
  36339. };
  36340. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  36341. light.transferToEffect(effect, lightIndex + "");
  36342. };
  36343. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  36344. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  36345. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  36346. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  36347. for (var i = 0; i < len; i++) {
  36348. var light = mesh._lightSources[i];
  36349. var iAsString = i.toString();
  36350. var scaledIntensity = light.getScaledIntensity();
  36351. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  36352. MaterialHelper.BindLightProperties(light, effect, i);
  36353. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  36354. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  36355. if (defines["SPECULARTERM"]) {
  36356. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  36357. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  36358. }
  36359. // Shadows
  36360. if (scene.shadowsEnabled) {
  36361. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  36362. }
  36363. light._uniformBuffer.update();
  36364. }
  36365. };
  36366. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  36367. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  36368. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  36369. effect.setColor3("vFogColor", scene.fogColor);
  36370. }
  36371. };
  36372. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  36373. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  36374. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  36375. if (matrices && effect) {
  36376. effect.setMatrices("mBones", matrices);
  36377. }
  36378. }
  36379. };
  36380. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  36381. var manager = abstractMesh.morphTargetManager;
  36382. if (!abstractMesh || !manager) {
  36383. return;
  36384. }
  36385. effect.setFloatArray("morphTargetInfluences", manager.influences);
  36386. };
  36387. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  36388. if (defines["LOGARITHMICDEPTH"]) {
  36389. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  36390. }
  36391. };
  36392. MaterialHelper.BindClipPlane = function (effect, scene) {
  36393. if (scene.clipPlane) {
  36394. var clipPlane = scene.clipPlane;
  36395. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  36396. }
  36397. };
  36398. return MaterialHelper;
  36399. }());
  36400. BABYLON.MaterialHelper = MaterialHelper;
  36401. })(BABYLON || (BABYLON = {}));
  36402. //# sourceMappingURL=babylon.materialHelper.js.map
  36403. var BABYLON;
  36404. (function (BABYLON) {
  36405. var PushMaterial = /** @class */ (function (_super) {
  36406. __extends(PushMaterial, _super);
  36407. function PushMaterial(name, scene) {
  36408. var _this = _super.call(this, name, scene) || this;
  36409. _this.storeEffectOnSubMeshes = true;
  36410. return _this;
  36411. }
  36412. PushMaterial.prototype.getEffect = function () {
  36413. return this._activeEffect;
  36414. };
  36415. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  36416. if (!mesh) {
  36417. return false;
  36418. }
  36419. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  36420. return true;
  36421. }
  36422. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  36423. };
  36424. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  36425. this._activeEffect.setMatrix("world", world);
  36426. };
  36427. PushMaterial.prototype.bind = function (world, mesh) {
  36428. if (!mesh) {
  36429. return;
  36430. }
  36431. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  36432. };
  36433. PushMaterial.prototype._afterBind = function (mesh, effect) {
  36434. if (effect === void 0) { effect = null; }
  36435. _super.prototype._afterBind.call(this, mesh);
  36436. this.getScene()._cachedEffect = effect;
  36437. };
  36438. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  36439. if (visibility === void 0) { visibility = 1; }
  36440. return scene.isCachedMaterialInvalid(this, effect, visibility);
  36441. };
  36442. return PushMaterial;
  36443. }(BABYLON.Material));
  36444. BABYLON.PushMaterial = PushMaterial;
  36445. })(BABYLON || (BABYLON = {}));
  36446. //# sourceMappingURL=babylon.pushMaterial.js.map
  36447. var BABYLON;
  36448. (function (BABYLON) {
  36449. var StandardMaterialDefines = /** @class */ (function (_super) {
  36450. __extends(StandardMaterialDefines, _super);
  36451. function StandardMaterialDefines() {
  36452. var _this = _super.call(this) || this;
  36453. _this.MAINUV1 = false;
  36454. _this.MAINUV2 = false;
  36455. _this.DIFFUSE = false;
  36456. _this.DIFFUSEDIRECTUV = 0;
  36457. _this.AMBIENT = false;
  36458. _this.AMBIENTDIRECTUV = 0;
  36459. _this.OPACITY = false;
  36460. _this.OPACITYDIRECTUV = 0;
  36461. _this.OPACITYRGB = false;
  36462. _this.REFLECTION = false;
  36463. _this.EMISSIVE = false;
  36464. _this.EMISSIVEDIRECTUV = 0;
  36465. _this.SPECULAR = false;
  36466. _this.SPECULARDIRECTUV = 0;
  36467. _this.BUMP = false;
  36468. _this.BUMPDIRECTUV = 0;
  36469. _this.PARALLAX = false;
  36470. _this.PARALLAXOCCLUSION = false;
  36471. _this.SPECULAROVERALPHA = false;
  36472. _this.CLIPPLANE = false;
  36473. _this.ALPHATEST = false;
  36474. _this.DEPTHPREPASS = false;
  36475. _this.ALPHAFROMDIFFUSE = false;
  36476. _this.POINTSIZE = false;
  36477. _this.FOG = false;
  36478. _this.SPECULARTERM = false;
  36479. _this.DIFFUSEFRESNEL = false;
  36480. _this.OPACITYFRESNEL = false;
  36481. _this.REFLECTIONFRESNEL = false;
  36482. _this.REFRACTIONFRESNEL = false;
  36483. _this.EMISSIVEFRESNEL = false;
  36484. _this.FRESNEL = false;
  36485. _this.NORMAL = false;
  36486. _this.UV1 = false;
  36487. _this.UV2 = false;
  36488. _this.VERTEXCOLOR = false;
  36489. _this.VERTEXALPHA = false;
  36490. _this.NUM_BONE_INFLUENCERS = 0;
  36491. _this.BonesPerMesh = 0;
  36492. _this.INSTANCES = false;
  36493. _this.GLOSSINESS = false;
  36494. _this.ROUGHNESS = false;
  36495. _this.EMISSIVEASILLUMINATION = false;
  36496. _this.LINKEMISSIVEWITHDIFFUSE = false;
  36497. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  36498. _this.LIGHTMAP = false;
  36499. _this.LIGHTMAPDIRECTUV = 0;
  36500. _this.USELIGHTMAPASSHADOWMAP = false;
  36501. _this.REFLECTIONMAP_3D = false;
  36502. _this.REFLECTIONMAP_SPHERICAL = false;
  36503. _this.REFLECTIONMAP_PLANAR = false;
  36504. _this.REFLECTIONMAP_CUBIC = false;
  36505. _this.REFLECTIONMAP_PROJECTION = false;
  36506. _this.REFLECTIONMAP_SKYBOX = false;
  36507. _this.REFLECTIONMAP_EXPLICIT = false;
  36508. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  36509. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  36510. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  36511. _this.INVERTCUBICMAP = false;
  36512. _this.LOGARITHMICDEPTH = false;
  36513. _this.REFRACTION = false;
  36514. _this.REFRACTIONMAP_3D = false;
  36515. _this.REFLECTIONOVERALPHA = false;
  36516. _this.TWOSIDEDLIGHTING = false;
  36517. _this.SHADOWFLOAT = false;
  36518. _this.MORPHTARGETS = false;
  36519. _this.MORPHTARGETS_NORMAL = false;
  36520. _this.MORPHTARGETS_TANGENT = false;
  36521. _this.NUM_MORPH_INFLUENCERS = 0;
  36522. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  36523. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  36524. _this.IMAGEPROCESSING = false;
  36525. _this.VIGNETTE = false;
  36526. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  36527. _this.VIGNETTEBLENDMODEOPAQUE = false;
  36528. _this.TONEMAPPING = false;
  36529. _this.CONTRAST = false;
  36530. _this.COLORCURVES = false;
  36531. _this.COLORGRADING = false;
  36532. _this.COLORGRADING3D = false;
  36533. _this.SAMPLER3DGREENDEPTH = false;
  36534. _this.SAMPLER3DBGRMAP = false;
  36535. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  36536. _this.EXPOSURE = false;
  36537. _this.rebuild();
  36538. return _this;
  36539. }
  36540. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  36541. var modes = [
  36542. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  36543. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  36544. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  36545. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  36546. ];
  36547. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  36548. var mode = modes_1[_i];
  36549. this[mode] = (mode === modeToEnable);
  36550. }
  36551. };
  36552. return StandardMaterialDefines;
  36553. }(BABYLON.MaterialDefines));
  36554. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  36555. var StandardMaterial = /** @class */ (function (_super) {
  36556. __extends(StandardMaterial, _super);
  36557. function StandardMaterial(name, scene) {
  36558. var _this = _super.call(this, name, scene) || this;
  36559. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  36560. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  36561. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  36562. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  36563. _this.specularPower = 64;
  36564. _this._useAlphaFromDiffuseTexture = false;
  36565. _this._useEmissiveAsIllumination = false;
  36566. _this._linkEmissiveWithDiffuse = false;
  36567. _this._useSpecularOverAlpha = false;
  36568. _this._useReflectionOverAlpha = false;
  36569. _this._disableLighting = false;
  36570. _this._useParallax = false;
  36571. _this._useParallaxOcclusion = false;
  36572. _this.parallaxScaleBias = 0.05;
  36573. _this._roughness = 0;
  36574. _this.indexOfRefraction = 0.98;
  36575. _this.invertRefractionY = true;
  36576. _this._useLightmapAsShadowmap = false;
  36577. _this._useReflectionFresnelFromSpecular = false;
  36578. _this._useGlossinessFromSpecularMapAlpha = false;
  36579. _this._maxSimultaneousLights = 4;
  36580. /**
  36581. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  36582. */
  36583. _this._invertNormalMapX = false;
  36584. /**
  36585. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  36586. */
  36587. _this._invertNormalMapY = false;
  36588. /**
  36589. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  36590. */
  36591. _this._twoSidedLighting = false;
  36592. _this._renderTargets = new BABYLON.SmartArray(16);
  36593. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  36594. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  36595. // Setup the default processing configuration to the scene.
  36596. _this._attachImageProcessingConfiguration(null);
  36597. _this.getRenderTargetTextures = function () {
  36598. _this._renderTargets.reset();
  36599. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  36600. _this._renderTargets.push(_this._reflectionTexture);
  36601. }
  36602. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  36603. _this._renderTargets.push(_this._refractionTexture);
  36604. }
  36605. return _this._renderTargets;
  36606. };
  36607. return _this;
  36608. }
  36609. ;
  36610. ;
  36611. ;
  36612. ;
  36613. ;
  36614. ;
  36615. ;
  36616. ;
  36617. ;
  36618. ;
  36619. ;
  36620. ;
  36621. ;
  36622. ;
  36623. ;
  36624. ;
  36625. ;
  36626. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  36627. /**
  36628. * Gets the image processing configuration used either in this material.
  36629. */
  36630. get: function () {
  36631. return this._imageProcessingConfiguration;
  36632. },
  36633. /**
  36634. * Sets the Default image processing configuration used either in the this material.
  36635. *
  36636. * If sets to null, the scene one is in use.
  36637. */
  36638. set: function (value) {
  36639. this._attachImageProcessingConfiguration(value);
  36640. // Ensure the effect will be rebuilt.
  36641. this._markAllSubMeshesAsTexturesDirty();
  36642. },
  36643. enumerable: true,
  36644. configurable: true
  36645. });
  36646. /**
  36647. * Attaches a new image processing configuration to the Standard Material.
  36648. * @param configuration
  36649. */
  36650. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  36651. var _this = this;
  36652. if (configuration === this._imageProcessingConfiguration) {
  36653. return;
  36654. }
  36655. // Detaches observer.
  36656. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  36657. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  36658. }
  36659. // Pick the scene configuration if needed.
  36660. if (!configuration) {
  36661. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  36662. }
  36663. else {
  36664. this._imageProcessingConfiguration = configuration;
  36665. }
  36666. // Attaches observer.
  36667. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  36668. _this._markAllSubMeshesAsImageProcessingDirty();
  36669. });
  36670. };
  36671. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  36672. /**
  36673. * Gets wether the color curves effect is enabled.
  36674. */
  36675. get: function () {
  36676. return this.imageProcessingConfiguration.colorCurvesEnabled;
  36677. },
  36678. /**
  36679. * Sets wether the color curves effect is enabled.
  36680. */
  36681. set: function (value) {
  36682. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  36683. },
  36684. enumerable: true,
  36685. configurable: true
  36686. });
  36687. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  36688. /**
  36689. * Gets wether the color grading effect is enabled.
  36690. */
  36691. get: function () {
  36692. return this.imageProcessingConfiguration.colorGradingEnabled;
  36693. },
  36694. /**
  36695. * Gets wether the color grading effect is enabled.
  36696. */
  36697. set: function (value) {
  36698. this.imageProcessingConfiguration.colorGradingEnabled = value;
  36699. },
  36700. enumerable: true,
  36701. configurable: true
  36702. });
  36703. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  36704. /**
  36705. * Gets wether tonemapping is enabled or not.
  36706. */
  36707. get: function () {
  36708. return this._imageProcessingConfiguration.toneMappingEnabled;
  36709. },
  36710. /**
  36711. * Sets wether tonemapping is enabled or not
  36712. */
  36713. set: function (value) {
  36714. this._imageProcessingConfiguration.toneMappingEnabled = value;
  36715. },
  36716. enumerable: true,
  36717. configurable: true
  36718. });
  36719. ;
  36720. ;
  36721. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  36722. /**
  36723. * The camera exposure used on this material.
  36724. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  36725. * This corresponds to a photographic exposure.
  36726. */
  36727. get: function () {
  36728. return this._imageProcessingConfiguration.exposure;
  36729. },
  36730. /**
  36731. * The camera exposure used on this material.
  36732. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  36733. * This corresponds to a photographic exposure.
  36734. */
  36735. set: function (value) {
  36736. this._imageProcessingConfiguration.exposure = value;
  36737. },
  36738. enumerable: true,
  36739. configurable: true
  36740. });
  36741. ;
  36742. ;
  36743. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  36744. /**
  36745. * Gets The camera contrast used on this material.
  36746. */
  36747. get: function () {
  36748. return this._imageProcessingConfiguration.contrast;
  36749. },
  36750. /**
  36751. * Sets The camera contrast used on this material.
  36752. */
  36753. set: function (value) {
  36754. this._imageProcessingConfiguration.contrast = value;
  36755. },
  36756. enumerable: true,
  36757. configurable: true
  36758. });
  36759. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  36760. /**
  36761. * Gets the Color Grading 2D Lookup Texture.
  36762. */
  36763. get: function () {
  36764. return this._imageProcessingConfiguration.colorGradingTexture;
  36765. },
  36766. /**
  36767. * Sets the Color Grading 2D Lookup Texture.
  36768. */
  36769. set: function (value) {
  36770. this._imageProcessingConfiguration.colorGradingTexture = value;
  36771. },
  36772. enumerable: true,
  36773. configurable: true
  36774. });
  36775. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  36776. /**
  36777. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  36778. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  36779. * 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;
  36780. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  36781. */
  36782. get: function () {
  36783. return this._imageProcessingConfiguration.colorCurves;
  36784. },
  36785. /**
  36786. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  36787. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  36788. * 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;
  36789. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  36790. */
  36791. set: function (value) {
  36792. this._imageProcessingConfiguration.colorCurves = value;
  36793. },
  36794. enumerable: true,
  36795. configurable: true
  36796. });
  36797. StandardMaterial.prototype.getClassName = function () {
  36798. return "StandardMaterial";
  36799. };
  36800. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  36801. get: function () {
  36802. return this._useLogarithmicDepth;
  36803. },
  36804. set: function (value) {
  36805. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  36806. this._markAllSubMeshesAsMiscDirty();
  36807. },
  36808. enumerable: true,
  36809. configurable: true
  36810. });
  36811. StandardMaterial.prototype.needAlphaBlending = function () {
  36812. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  36813. };
  36814. StandardMaterial.prototype.needAlphaTesting = function () {
  36815. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  36816. };
  36817. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  36818. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  36819. };
  36820. StandardMaterial.prototype.getAlphaTestTexture = function () {
  36821. return this._diffuseTexture;
  36822. };
  36823. /**
  36824. * Child classes can use it to update shaders
  36825. */
  36826. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  36827. if (useInstances === void 0) { useInstances = false; }
  36828. if (subMesh.effect && this.isFrozen) {
  36829. if (this._wasPreviouslyReady && subMesh.effect) {
  36830. return true;
  36831. }
  36832. }
  36833. if (!subMesh._materialDefines) {
  36834. subMesh._materialDefines = new StandardMaterialDefines();
  36835. }
  36836. var scene = this.getScene();
  36837. var defines = subMesh._materialDefines;
  36838. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  36839. if (defines._renderId === scene.getRenderId()) {
  36840. return true;
  36841. }
  36842. }
  36843. var engine = scene.getEngine();
  36844. // Lights
  36845. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  36846. // Textures
  36847. if (defines._areTexturesDirty) {
  36848. defines._needUVs = false;
  36849. defines.MAINUV1 = false;
  36850. defines.MAINUV2 = false;
  36851. if (scene.texturesEnabled) {
  36852. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  36853. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  36854. return false;
  36855. }
  36856. else {
  36857. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  36858. }
  36859. }
  36860. else {
  36861. defines.DIFFUSE = false;
  36862. }
  36863. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  36864. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  36865. return false;
  36866. }
  36867. else {
  36868. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  36869. }
  36870. }
  36871. else {
  36872. defines.AMBIENT = false;
  36873. }
  36874. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  36875. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  36876. return false;
  36877. }
  36878. else {
  36879. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  36880. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  36881. }
  36882. }
  36883. else {
  36884. defines.OPACITY = false;
  36885. }
  36886. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  36887. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  36888. return false;
  36889. }
  36890. else {
  36891. defines._needNormals = true;
  36892. defines.REFLECTION = true;
  36893. defines.ROUGHNESS = (this._roughness > 0);
  36894. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  36895. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  36896. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  36897. switch (this._reflectionTexture.coordinatesMode) {
  36898. case BABYLON.Texture.CUBIC_MODE:
  36899. case BABYLON.Texture.INVCUBIC_MODE:
  36900. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  36901. break;
  36902. case BABYLON.Texture.EXPLICIT_MODE:
  36903. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  36904. break;
  36905. case BABYLON.Texture.PLANAR_MODE:
  36906. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  36907. break;
  36908. case BABYLON.Texture.PROJECTION_MODE:
  36909. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  36910. break;
  36911. case BABYLON.Texture.SKYBOX_MODE:
  36912. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  36913. break;
  36914. case BABYLON.Texture.SPHERICAL_MODE:
  36915. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  36916. break;
  36917. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  36918. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  36919. break;
  36920. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  36921. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  36922. break;
  36923. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  36924. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  36925. break;
  36926. }
  36927. }
  36928. }
  36929. else {
  36930. defines.REFLECTION = false;
  36931. }
  36932. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  36933. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  36934. return false;
  36935. }
  36936. else {
  36937. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  36938. }
  36939. }
  36940. else {
  36941. defines.EMISSIVE = false;
  36942. }
  36943. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  36944. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  36945. return false;
  36946. }
  36947. else {
  36948. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  36949. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  36950. }
  36951. }
  36952. else {
  36953. defines.LIGHTMAP = false;
  36954. }
  36955. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  36956. if (!this._specularTexture.isReadyOrNotBlocking()) {
  36957. return false;
  36958. }
  36959. else {
  36960. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  36961. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  36962. }
  36963. }
  36964. else {
  36965. defines.SPECULAR = false;
  36966. }
  36967. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  36968. // Bump texure can not be not blocking.
  36969. if (!this._bumpTexture.isReady()) {
  36970. return false;
  36971. }
  36972. else {
  36973. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  36974. defines.PARALLAX = this._useParallax;
  36975. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  36976. }
  36977. }
  36978. else {
  36979. defines.BUMP = false;
  36980. }
  36981. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  36982. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  36983. return false;
  36984. }
  36985. else {
  36986. defines._needUVs = true;
  36987. defines.REFRACTION = true;
  36988. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  36989. }
  36990. }
  36991. else {
  36992. defines.REFRACTION = false;
  36993. }
  36994. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  36995. }
  36996. else {
  36997. defines.DIFFUSE = false;
  36998. defines.AMBIENT = false;
  36999. defines.OPACITY = false;
  37000. defines.REFLECTION = false;
  37001. defines.EMISSIVE = false;
  37002. defines.LIGHTMAP = false;
  37003. defines.BUMP = false;
  37004. defines.REFRACTION = false;
  37005. }
  37006. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  37007. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  37008. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  37009. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  37010. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  37011. }
  37012. if (defines._areImageProcessingDirty) {
  37013. if (!this._imageProcessingConfiguration.isReady()) {
  37014. return false;
  37015. }
  37016. this._imageProcessingConfiguration.prepareDefines(defines);
  37017. }
  37018. if (defines._areFresnelDirty) {
  37019. if (StandardMaterial.FresnelEnabled) {
  37020. // Fresnel
  37021. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  37022. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  37023. this._reflectionFresnelParameters) {
  37024. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  37025. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  37026. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  37027. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  37028. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  37029. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  37030. defines._needNormals = true;
  37031. defines.FRESNEL = true;
  37032. }
  37033. }
  37034. else {
  37035. defines.FRESNEL = false;
  37036. }
  37037. }
  37038. // Misc.
  37039. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  37040. // Attribs
  37041. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  37042. // Values that need to be evaluated on every frame
  37043. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  37044. // Get correct effect
  37045. if (defines.isDirty) {
  37046. defines.markAsProcessed();
  37047. scene.resetCachedMaterial();
  37048. // Fallbacks
  37049. var fallbacks = new BABYLON.EffectFallbacks();
  37050. if (defines.REFLECTION) {
  37051. fallbacks.addFallback(0, "REFLECTION");
  37052. }
  37053. if (defines.SPECULAR) {
  37054. fallbacks.addFallback(0, "SPECULAR");
  37055. }
  37056. if (defines.BUMP) {
  37057. fallbacks.addFallback(0, "BUMP");
  37058. }
  37059. if (defines.PARALLAX) {
  37060. fallbacks.addFallback(1, "PARALLAX");
  37061. }
  37062. if (defines.PARALLAXOCCLUSION) {
  37063. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  37064. }
  37065. if (defines.SPECULAROVERALPHA) {
  37066. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  37067. }
  37068. if (defines.FOG) {
  37069. fallbacks.addFallback(1, "FOG");
  37070. }
  37071. if (defines.POINTSIZE) {
  37072. fallbacks.addFallback(0, "POINTSIZE");
  37073. }
  37074. if (defines.LOGARITHMICDEPTH) {
  37075. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  37076. }
  37077. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  37078. if (defines.SPECULARTERM) {
  37079. fallbacks.addFallback(0, "SPECULARTERM");
  37080. }
  37081. if (defines.DIFFUSEFRESNEL) {
  37082. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  37083. }
  37084. if (defines.OPACITYFRESNEL) {
  37085. fallbacks.addFallback(2, "OPACITYFRESNEL");
  37086. }
  37087. if (defines.REFLECTIONFRESNEL) {
  37088. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  37089. }
  37090. if (defines.EMISSIVEFRESNEL) {
  37091. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  37092. }
  37093. if (defines.FRESNEL) {
  37094. fallbacks.addFallback(4, "FRESNEL");
  37095. }
  37096. //Attributes
  37097. var attribs = [BABYLON.VertexBuffer.PositionKind];
  37098. if (defines.NORMAL) {
  37099. attribs.push(BABYLON.VertexBuffer.NormalKind);
  37100. }
  37101. if (defines.UV1) {
  37102. attribs.push(BABYLON.VertexBuffer.UVKind);
  37103. }
  37104. if (defines.UV2) {
  37105. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  37106. }
  37107. if (defines.VERTEXCOLOR) {
  37108. attribs.push(BABYLON.VertexBuffer.ColorKind);
  37109. }
  37110. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  37111. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  37112. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  37113. var shaderName = "default";
  37114. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  37115. "vFogInfos", "vFogColor", "pointSize",
  37116. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  37117. "mBones",
  37118. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  37119. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  37120. "logarithmicDepthConstant", "vTangentSpaceParams"
  37121. ];
  37122. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  37123. var uniformBuffers = ["Material", "Scene"];
  37124. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  37125. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  37126. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  37127. uniformsNames: uniforms,
  37128. uniformBuffersNames: uniformBuffers,
  37129. samplers: samplers,
  37130. defines: defines,
  37131. maxSimultaneousLights: this._maxSimultaneousLights
  37132. });
  37133. if (this.customShaderNameResolve) {
  37134. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  37135. }
  37136. var join = defines.toString();
  37137. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  37138. attributes: attribs,
  37139. uniformsNames: uniforms,
  37140. uniformBuffersNames: uniformBuffers,
  37141. samplers: samplers,
  37142. defines: join,
  37143. fallbacks: fallbacks,
  37144. onCompiled: this.onCompiled,
  37145. onError: this.onError,
  37146. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  37147. }, engine), defines);
  37148. this.buildUniformLayout();
  37149. }
  37150. if (!subMesh.effect || !subMesh.effect.isReady()) {
  37151. return false;
  37152. }
  37153. defines._renderId = scene.getRenderId();
  37154. this._wasPreviouslyReady = true;
  37155. return true;
  37156. };
  37157. StandardMaterial.prototype.buildUniformLayout = function () {
  37158. // Order is important !
  37159. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  37160. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  37161. this._uniformBuffer.addUniform("opacityParts", 4);
  37162. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  37163. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  37164. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  37165. this._uniformBuffer.addUniform("refractionRightColor", 4);
  37166. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  37167. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  37168. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  37169. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  37170. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  37171. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  37172. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  37173. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  37174. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  37175. this._uniformBuffer.addUniform("vBumpInfos", 3);
  37176. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  37177. this._uniformBuffer.addUniform("ambientMatrix", 16);
  37178. this._uniformBuffer.addUniform("opacityMatrix", 16);
  37179. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  37180. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  37181. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  37182. this._uniformBuffer.addUniform("specularMatrix", 16);
  37183. this._uniformBuffer.addUniform("bumpMatrix", 16);
  37184. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  37185. this._uniformBuffer.addUniform("refractionMatrix", 16);
  37186. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  37187. this._uniformBuffer.addUniform("vSpecularColor", 4);
  37188. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  37189. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  37190. this._uniformBuffer.addUniform("pointSize", 1);
  37191. this._uniformBuffer.create();
  37192. };
  37193. StandardMaterial.prototype.unbind = function () {
  37194. if (this._activeEffect) {
  37195. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  37196. this._activeEffect.setTexture("reflection2DSampler", null);
  37197. }
  37198. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  37199. this._activeEffect.setTexture("refraction2DSampler", null);
  37200. }
  37201. }
  37202. _super.prototype.unbind.call(this);
  37203. };
  37204. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  37205. var scene = this.getScene();
  37206. var defines = subMesh._materialDefines;
  37207. if (!defines) {
  37208. return;
  37209. }
  37210. var effect = subMesh.effect;
  37211. if (!effect) {
  37212. return;
  37213. }
  37214. this._activeEffect = effect;
  37215. // Matrices
  37216. this.bindOnlyWorldMatrix(world);
  37217. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  37218. // Bones
  37219. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  37220. if (mustRebind) {
  37221. this._uniformBuffer.bindToEffect(effect, "Material");
  37222. this.bindViewProjection(effect);
  37223. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  37224. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  37225. // Fresnel
  37226. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  37227. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  37228. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  37229. }
  37230. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  37231. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  37232. }
  37233. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  37234. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  37235. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  37236. }
  37237. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  37238. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  37239. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  37240. }
  37241. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  37242. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  37243. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  37244. }
  37245. }
  37246. // Textures
  37247. if (scene.texturesEnabled) {
  37248. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  37249. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  37250. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  37251. }
  37252. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  37253. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  37254. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  37255. }
  37256. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  37257. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  37258. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  37259. }
  37260. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  37261. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  37262. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  37263. }
  37264. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  37265. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  37266. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  37267. }
  37268. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  37269. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  37270. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  37271. }
  37272. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  37273. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  37274. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  37275. }
  37276. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  37277. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  37278. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  37279. if (scene._mirroredCameraPosition) {
  37280. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  37281. }
  37282. else {
  37283. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  37284. }
  37285. }
  37286. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  37287. var depth = 1.0;
  37288. if (!this._refractionTexture.isCube) {
  37289. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  37290. if (this._refractionTexture.depth) {
  37291. depth = this._refractionTexture.depth;
  37292. }
  37293. }
  37294. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  37295. }
  37296. }
  37297. // Point size
  37298. if (this.pointsCloud) {
  37299. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  37300. }
  37301. if (defines.SPECULARTERM) {
  37302. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  37303. }
  37304. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  37305. // Diffuse
  37306. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  37307. }
  37308. // Textures
  37309. if (scene.texturesEnabled) {
  37310. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  37311. effect.setTexture("diffuseSampler", this._diffuseTexture);
  37312. }
  37313. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  37314. effect.setTexture("ambientSampler", this._ambientTexture);
  37315. }
  37316. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  37317. effect.setTexture("opacitySampler", this._opacityTexture);
  37318. }
  37319. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  37320. if (this._reflectionTexture.isCube) {
  37321. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  37322. }
  37323. else {
  37324. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  37325. }
  37326. }
  37327. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  37328. effect.setTexture("emissiveSampler", this._emissiveTexture);
  37329. }
  37330. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  37331. effect.setTexture("lightmapSampler", this._lightmapTexture);
  37332. }
  37333. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  37334. effect.setTexture("specularSampler", this._specularTexture);
  37335. }
  37336. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  37337. effect.setTexture("bumpSampler", this._bumpTexture);
  37338. }
  37339. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  37340. var depth = 1.0;
  37341. if (this._refractionTexture.isCube) {
  37342. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  37343. }
  37344. else {
  37345. effect.setTexture("refraction2DSampler", this._refractionTexture);
  37346. }
  37347. }
  37348. }
  37349. // Clip plane
  37350. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  37351. // Colors
  37352. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  37353. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  37354. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  37355. }
  37356. if (mustRebind || !this.isFrozen) {
  37357. // Lights
  37358. if (scene.lightsEnabled && !this._disableLighting) {
  37359. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  37360. }
  37361. // View
  37362. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  37363. this.bindView(effect);
  37364. }
  37365. // Fog
  37366. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  37367. // Morph targets
  37368. if (defines.NUM_MORPH_INFLUENCERS) {
  37369. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  37370. }
  37371. // Log. depth
  37372. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  37373. // image processing
  37374. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  37375. this._imageProcessingConfiguration.bind(this._activeEffect);
  37376. }
  37377. }
  37378. this._uniformBuffer.update();
  37379. this._afterBind(mesh, this._activeEffect);
  37380. };
  37381. StandardMaterial.prototype.getAnimatables = function () {
  37382. var results = [];
  37383. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  37384. results.push(this._diffuseTexture);
  37385. }
  37386. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  37387. results.push(this._ambientTexture);
  37388. }
  37389. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  37390. results.push(this._opacityTexture);
  37391. }
  37392. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  37393. results.push(this._reflectionTexture);
  37394. }
  37395. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  37396. results.push(this._emissiveTexture);
  37397. }
  37398. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  37399. results.push(this._specularTexture);
  37400. }
  37401. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  37402. results.push(this._bumpTexture);
  37403. }
  37404. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  37405. results.push(this._lightmapTexture);
  37406. }
  37407. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  37408. results.push(this._refractionTexture);
  37409. }
  37410. return results;
  37411. };
  37412. StandardMaterial.prototype.getActiveTextures = function () {
  37413. var activeTextures = _super.prototype.getActiveTextures.call(this);
  37414. if (this._diffuseTexture) {
  37415. activeTextures.push(this._diffuseTexture);
  37416. }
  37417. if (this._ambientTexture) {
  37418. activeTextures.push(this._ambientTexture);
  37419. }
  37420. if (this._opacityTexture) {
  37421. activeTextures.push(this._opacityTexture);
  37422. }
  37423. if (this._reflectionTexture) {
  37424. activeTextures.push(this._reflectionTexture);
  37425. }
  37426. if (this._emissiveTexture) {
  37427. activeTextures.push(this._emissiveTexture);
  37428. }
  37429. if (this._specularTexture) {
  37430. activeTextures.push(this._specularTexture);
  37431. }
  37432. if (this._bumpTexture) {
  37433. activeTextures.push(this._bumpTexture);
  37434. }
  37435. if (this._lightmapTexture) {
  37436. activeTextures.push(this._lightmapTexture);
  37437. }
  37438. if (this._refractionTexture) {
  37439. activeTextures.push(this._refractionTexture);
  37440. }
  37441. return activeTextures;
  37442. };
  37443. StandardMaterial.prototype.hasTexture = function (texture) {
  37444. if (_super.prototype.hasTexture.call(this, texture)) {
  37445. return true;
  37446. }
  37447. if (this._diffuseTexture === texture) {
  37448. return true;
  37449. }
  37450. if (this._ambientTexture === texture) {
  37451. return true;
  37452. }
  37453. if (this._opacityTexture === texture) {
  37454. return true;
  37455. }
  37456. if (this._reflectionTexture === texture) {
  37457. return true;
  37458. }
  37459. if (this._emissiveTexture === texture) {
  37460. return true;
  37461. }
  37462. if (this._specularTexture === texture) {
  37463. return true;
  37464. }
  37465. if (this._bumpTexture === texture) {
  37466. return true;
  37467. }
  37468. if (this._lightmapTexture === texture) {
  37469. return true;
  37470. }
  37471. if (this._refractionTexture === texture) {
  37472. return true;
  37473. }
  37474. return false;
  37475. };
  37476. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  37477. if (forceDisposeTextures) {
  37478. if (this._diffuseTexture) {
  37479. this._diffuseTexture.dispose();
  37480. }
  37481. if (this._ambientTexture) {
  37482. this._ambientTexture.dispose();
  37483. }
  37484. if (this._opacityTexture) {
  37485. this._opacityTexture.dispose();
  37486. }
  37487. if (this._reflectionTexture) {
  37488. this._reflectionTexture.dispose();
  37489. }
  37490. if (this._emissiveTexture) {
  37491. this._emissiveTexture.dispose();
  37492. }
  37493. if (this._specularTexture) {
  37494. this._specularTexture.dispose();
  37495. }
  37496. if (this._bumpTexture) {
  37497. this._bumpTexture.dispose();
  37498. }
  37499. if (this._lightmapTexture) {
  37500. this._lightmapTexture.dispose();
  37501. }
  37502. if (this._refractionTexture) {
  37503. this._refractionTexture.dispose();
  37504. }
  37505. }
  37506. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  37507. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  37508. }
  37509. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  37510. };
  37511. StandardMaterial.prototype.clone = function (name) {
  37512. var _this = this;
  37513. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  37514. result.name = name;
  37515. result.id = name;
  37516. return result;
  37517. };
  37518. StandardMaterial.prototype.serialize = function () {
  37519. return BABYLON.SerializationHelper.Serialize(this);
  37520. };
  37521. // Statics
  37522. StandardMaterial.Parse = function (source, scene, rootUrl) {
  37523. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  37524. };
  37525. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  37526. get: function () {
  37527. return StandardMaterial._DiffuseTextureEnabled;
  37528. },
  37529. set: function (value) {
  37530. if (StandardMaterial._DiffuseTextureEnabled === value) {
  37531. return;
  37532. }
  37533. StandardMaterial._DiffuseTextureEnabled = value;
  37534. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37535. },
  37536. enumerable: true,
  37537. configurable: true
  37538. });
  37539. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  37540. get: function () {
  37541. return StandardMaterial._AmbientTextureEnabled;
  37542. },
  37543. set: function (value) {
  37544. if (StandardMaterial._AmbientTextureEnabled === value) {
  37545. return;
  37546. }
  37547. StandardMaterial._AmbientTextureEnabled = value;
  37548. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37549. },
  37550. enumerable: true,
  37551. configurable: true
  37552. });
  37553. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  37554. get: function () {
  37555. return StandardMaterial._OpacityTextureEnabled;
  37556. },
  37557. set: function (value) {
  37558. if (StandardMaterial._OpacityTextureEnabled === value) {
  37559. return;
  37560. }
  37561. StandardMaterial._OpacityTextureEnabled = value;
  37562. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37563. },
  37564. enumerable: true,
  37565. configurable: true
  37566. });
  37567. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  37568. get: function () {
  37569. return StandardMaterial._ReflectionTextureEnabled;
  37570. },
  37571. set: function (value) {
  37572. if (StandardMaterial._ReflectionTextureEnabled === value) {
  37573. return;
  37574. }
  37575. StandardMaterial._ReflectionTextureEnabled = value;
  37576. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37577. },
  37578. enumerable: true,
  37579. configurable: true
  37580. });
  37581. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  37582. get: function () {
  37583. return StandardMaterial._EmissiveTextureEnabled;
  37584. },
  37585. set: function (value) {
  37586. if (StandardMaterial._EmissiveTextureEnabled === value) {
  37587. return;
  37588. }
  37589. StandardMaterial._EmissiveTextureEnabled = value;
  37590. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37591. },
  37592. enumerable: true,
  37593. configurable: true
  37594. });
  37595. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  37596. get: function () {
  37597. return StandardMaterial._SpecularTextureEnabled;
  37598. },
  37599. set: function (value) {
  37600. if (StandardMaterial._SpecularTextureEnabled === value) {
  37601. return;
  37602. }
  37603. StandardMaterial._SpecularTextureEnabled = value;
  37604. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37605. },
  37606. enumerable: true,
  37607. configurable: true
  37608. });
  37609. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  37610. get: function () {
  37611. return StandardMaterial._BumpTextureEnabled;
  37612. },
  37613. set: function (value) {
  37614. if (StandardMaterial._BumpTextureEnabled === value) {
  37615. return;
  37616. }
  37617. StandardMaterial._BumpTextureEnabled = value;
  37618. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37619. },
  37620. enumerable: true,
  37621. configurable: true
  37622. });
  37623. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  37624. get: function () {
  37625. return StandardMaterial._LightmapTextureEnabled;
  37626. },
  37627. set: function (value) {
  37628. if (StandardMaterial._LightmapTextureEnabled === value) {
  37629. return;
  37630. }
  37631. StandardMaterial._LightmapTextureEnabled = value;
  37632. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37633. },
  37634. enumerable: true,
  37635. configurable: true
  37636. });
  37637. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  37638. get: function () {
  37639. return StandardMaterial._RefractionTextureEnabled;
  37640. },
  37641. set: function (value) {
  37642. if (StandardMaterial._RefractionTextureEnabled === value) {
  37643. return;
  37644. }
  37645. StandardMaterial._RefractionTextureEnabled = value;
  37646. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37647. },
  37648. enumerable: true,
  37649. configurable: true
  37650. });
  37651. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  37652. get: function () {
  37653. return StandardMaterial._ColorGradingTextureEnabled;
  37654. },
  37655. set: function (value) {
  37656. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  37657. return;
  37658. }
  37659. StandardMaterial._ColorGradingTextureEnabled = value;
  37660. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37661. },
  37662. enumerable: true,
  37663. configurable: true
  37664. });
  37665. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  37666. get: function () {
  37667. return StandardMaterial._FresnelEnabled;
  37668. },
  37669. set: function (value) {
  37670. if (StandardMaterial._FresnelEnabled === value) {
  37671. return;
  37672. }
  37673. StandardMaterial._FresnelEnabled = value;
  37674. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  37675. },
  37676. enumerable: true,
  37677. configurable: true
  37678. });
  37679. // Flags used to enable or disable a type of texture for all Standard Materials
  37680. StandardMaterial._DiffuseTextureEnabled = true;
  37681. StandardMaterial._AmbientTextureEnabled = true;
  37682. StandardMaterial._OpacityTextureEnabled = true;
  37683. StandardMaterial._ReflectionTextureEnabled = true;
  37684. StandardMaterial._EmissiveTextureEnabled = true;
  37685. StandardMaterial._SpecularTextureEnabled = true;
  37686. StandardMaterial._BumpTextureEnabled = true;
  37687. StandardMaterial._LightmapTextureEnabled = true;
  37688. StandardMaterial._RefractionTextureEnabled = true;
  37689. StandardMaterial._ColorGradingTextureEnabled = true;
  37690. StandardMaterial._FresnelEnabled = true;
  37691. __decorate([
  37692. BABYLON.serializeAsTexture("diffuseTexture")
  37693. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  37694. __decorate([
  37695. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  37696. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  37697. __decorate([
  37698. BABYLON.serializeAsTexture("ambientTexture")
  37699. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  37700. __decorate([
  37701. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37702. ], StandardMaterial.prototype, "ambientTexture", void 0);
  37703. __decorate([
  37704. BABYLON.serializeAsTexture("opacityTexture")
  37705. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  37706. __decorate([
  37707. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  37708. ], StandardMaterial.prototype, "opacityTexture", void 0);
  37709. __decorate([
  37710. BABYLON.serializeAsTexture("reflectionTexture")
  37711. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  37712. __decorate([
  37713. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37714. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  37715. __decorate([
  37716. BABYLON.serializeAsTexture("emissiveTexture")
  37717. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  37718. __decorate([
  37719. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37720. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  37721. __decorate([
  37722. BABYLON.serializeAsTexture("specularTexture")
  37723. ], StandardMaterial.prototype, "_specularTexture", void 0);
  37724. __decorate([
  37725. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37726. ], StandardMaterial.prototype, "specularTexture", void 0);
  37727. __decorate([
  37728. BABYLON.serializeAsTexture("bumpTexture")
  37729. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  37730. __decorate([
  37731. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37732. ], StandardMaterial.prototype, "bumpTexture", void 0);
  37733. __decorate([
  37734. BABYLON.serializeAsTexture("lightmapTexture")
  37735. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  37736. __decorate([
  37737. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37738. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  37739. __decorate([
  37740. BABYLON.serializeAsTexture("refractionTexture")
  37741. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  37742. __decorate([
  37743. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37744. ], StandardMaterial.prototype, "refractionTexture", void 0);
  37745. __decorate([
  37746. BABYLON.serializeAsColor3("ambient")
  37747. ], StandardMaterial.prototype, "ambientColor", void 0);
  37748. __decorate([
  37749. BABYLON.serializeAsColor3("diffuse")
  37750. ], StandardMaterial.prototype, "diffuseColor", void 0);
  37751. __decorate([
  37752. BABYLON.serializeAsColor3("specular")
  37753. ], StandardMaterial.prototype, "specularColor", void 0);
  37754. __decorate([
  37755. BABYLON.serializeAsColor3("emissive")
  37756. ], StandardMaterial.prototype, "emissiveColor", void 0);
  37757. __decorate([
  37758. BABYLON.serialize()
  37759. ], StandardMaterial.prototype, "specularPower", void 0);
  37760. __decorate([
  37761. BABYLON.serialize("useAlphaFromDiffuseTexture")
  37762. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  37763. __decorate([
  37764. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37765. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  37766. __decorate([
  37767. BABYLON.serialize("useEmissiveAsIllumination")
  37768. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  37769. __decorate([
  37770. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37771. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  37772. __decorate([
  37773. BABYLON.serialize("linkEmissiveWithDiffuse")
  37774. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  37775. __decorate([
  37776. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37777. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  37778. __decorate([
  37779. BABYLON.serialize("useSpecularOverAlpha")
  37780. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  37781. __decorate([
  37782. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37783. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  37784. __decorate([
  37785. BABYLON.serialize("useReflectionOverAlpha")
  37786. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  37787. __decorate([
  37788. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37789. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  37790. __decorate([
  37791. BABYLON.serialize("disableLighting")
  37792. ], StandardMaterial.prototype, "_disableLighting", void 0);
  37793. __decorate([
  37794. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37795. ], StandardMaterial.prototype, "disableLighting", void 0);
  37796. __decorate([
  37797. BABYLON.serialize("useParallax")
  37798. ], StandardMaterial.prototype, "_useParallax", void 0);
  37799. __decorate([
  37800. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37801. ], StandardMaterial.prototype, "useParallax", void 0);
  37802. __decorate([
  37803. BABYLON.serialize("useParallaxOcclusion")
  37804. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  37805. __decorate([
  37806. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37807. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  37808. __decorate([
  37809. BABYLON.serialize()
  37810. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  37811. __decorate([
  37812. BABYLON.serialize("roughness")
  37813. ], StandardMaterial.prototype, "_roughness", void 0);
  37814. __decorate([
  37815. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37816. ], StandardMaterial.prototype, "roughness", void 0);
  37817. __decorate([
  37818. BABYLON.serialize()
  37819. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  37820. __decorate([
  37821. BABYLON.serialize()
  37822. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  37823. __decorate([
  37824. BABYLON.serialize("useLightmapAsShadowmap")
  37825. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  37826. __decorate([
  37827. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37828. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  37829. __decorate([
  37830. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  37831. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  37832. __decorate([
  37833. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  37834. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  37835. __decorate([
  37836. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  37837. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  37838. __decorate([
  37839. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  37840. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  37841. __decorate([
  37842. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  37843. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  37844. __decorate([
  37845. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  37846. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  37847. __decorate([
  37848. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  37849. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  37850. __decorate([
  37851. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  37852. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  37853. __decorate([
  37854. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  37855. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  37856. __decorate([
  37857. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  37858. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  37859. __decorate([
  37860. BABYLON.serialize("useReflectionFresnelFromSpecular")
  37861. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  37862. __decorate([
  37863. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  37864. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  37865. __decorate([
  37866. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  37867. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  37868. __decorate([
  37869. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37870. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  37871. __decorate([
  37872. BABYLON.serialize("maxSimultaneousLights")
  37873. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  37874. __decorate([
  37875. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37876. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  37877. __decorate([
  37878. BABYLON.serialize("invertNormalMapX")
  37879. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  37880. __decorate([
  37881. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37882. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  37883. __decorate([
  37884. BABYLON.serialize("invertNormalMapY")
  37885. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  37886. __decorate([
  37887. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37888. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  37889. __decorate([
  37890. BABYLON.serialize("twoSidedLighting")
  37891. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  37892. __decorate([
  37893. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37894. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  37895. __decorate([
  37896. BABYLON.serialize()
  37897. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  37898. return StandardMaterial;
  37899. }(BABYLON.PushMaterial));
  37900. BABYLON.StandardMaterial = StandardMaterial;
  37901. })(BABYLON || (BABYLON = {}));
  37902. //# sourceMappingURL=babylon.standardMaterial.js.map
  37903. var BABYLON;
  37904. (function (BABYLON) {
  37905. var PBRMaterialDefines = /** @class */ (function (_super) {
  37906. __extends(PBRMaterialDefines, _super);
  37907. function PBRMaterialDefines() {
  37908. var _this = _super.call(this) || this;
  37909. _this.PBR = true;
  37910. _this.MAINUV1 = false;
  37911. _this.MAINUV2 = false;
  37912. _this.UV1 = false;
  37913. _this.UV2 = false;
  37914. _this.ALBEDO = false;
  37915. _this.ALBEDODIRECTUV = 0;
  37916. _this.VERTEXCOLOR = false;
  37917. _this.AMBIENT = false;
  37918. _this.AMBIENTDIRECTUV = 0;
  37919. _this.AMBIENTINGRAYSCALE = false;
  37920. _this.OPACITY = false;
  37921. _this.VERTEXALPHA = false;
  37922. _this.OPACITYDIRECTUV = 0;
  37923. _this.OPACITYRGB = false;
  37924. _this.ALPHATEST = false;
  37925. _this.DEPTHPREPASS = false;
  37926. _this.ALPHABLEND = false;
  37927. _this.ALPHAFROMALBEDO = false;
  37928. _this.ALPHATESTVALUE = 0.5;
  37929. _this.SPECULAROVERALPHA = false;
  37930. _this.RADIANCEOVERALPHA = false;
  37931. _this.ALPHAFRESNEL = false;
  37932. _this.LINEARALPHAFRESNEL = false;
  37933. _this.PREMULTIPLYALPHA = false;
  37934. _this.EMISSIVE = false;
  37935. _this.EMISSIVEDIRECTUV = 0;
  37936. _this.REFLECTIVITY = false;
  37937. _this.REFLECTIVITYDIRECTUV = 0;
  37938. _this.SPECULARTERM = false;
  37939. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  37940. _this.MICROSURFACEAUTOMATIC = false;
  37941. _this.LODBASEDMICROSFURACE = false;
  37942. _this.MICROSURFACEMAP = false;
  37943. _this.MICROSURFACEMAPDIRECTUV = 0;
  37944. _this.METALLICWORKFLOW = false;
  37945. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  37946. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  37947. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  37948. _this.AOSTOREINMETALMAPRED = false;
  37949. _this.ENVIRONMENTBRDF = false;
  37950. _this.NORMAL = false;
  37951. _this.TANGENT = false;
  37952. _this.BUMP = false;
  37953. _this.BUMPDIRECTUV = 0;
  37954. _this.PARALLAX = false;
  37955. _this.PARALLAXOCCLUSION = false;
  37956. _this.NORMALXYSCALE = true;
  37957. _this.LIGHTMAP = false;
  37958. _this.LIGHTMAPDIRECTUV = 0;
  37959. _this.USELIGHTMAPASSHADOWMAP = false;
  37960. _this.REFLECTION = false;
  37961. _this.REFLECTIONMAP_3D = false;
  37962. _this.REFLECTIONMAP_SPHERICAL = false;
  37963. _this.REFLECTIONMAP_PLANAR = false;
  37964. _this.REFLECTIONMAP_CUBIC = false;
  37965. _this.REFLECTIONMAP_PROJECTION = false;
  37966. _this.REFLECTIONMAP_SKYBOX = false;
  37967. _this.REFLECTIONMAP_EXPLICIT = false;
  37968. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  37969. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  37970. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  37971. _this.INVERTCUBICMAP = false;
  37972. _this.USESPHERICALFROMREFLECTIONMAP = false;
  37973. _this.USESPHERICALINVERTEX = false;
  37974. _this.REFLECTIONMAP_OPPOSITEZ = false;
  37975. _this.LODINREFLECTIONALPHA = false;
  37976. _this.GAMMAREFLECTION = false;
  37977. _this.RADIANCEOCCLUSION = false;
  37978. _this.HORIZONOCCLUSION = false;
  37979. _this.REFRACTION = false;
  37980. _this.REFRACTIONMAP_3D = false;
  37981. _this.REFRACTIONMAP_OPPOSITEZ = false;
  37982. _this.LODINREFRACTIONALPHA = false;
  37983. _this.GAMMAREFRACTION = false;
  37984. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  37985. _this.INSTANCES = false;
  37986. _this.NUM_BONE_INFLUENCERS = 0;
  37987. _this.BonesPerMesh = 0;
  37988. _this.NONUNIFORMSCALING = false;
  37989. _this.MORPHTARGETS = false;
  37990. _this.MORPHTARGETS_NORMAL = false;
  37991. _this.MORPHTARGETS_TANGENT = false;
  37992. _this.NUM_MORPH_INFLUENCERS = 0;
  37993. _this.IMAGEPROCESSING = false;
  37994. _this.VIGNETTE = false;
  37995. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  37996. _this.VIGNETTEBLENDMODEOPAQUE = false;
  37997. _this.TONEMAPPING = false;
  37998. _this.CONTRAST = false;
  37999. _this.COLORCURVES = false;
  38000. _this.COLORGRADING = false;
  38001. _this.COLORGRADING3D = false;
  38002. _this.SAMPLER3DGREENDEPTH = false;
  38003. _this.SAMPLER3DBGRMAP = false;
  38004. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  38005. _this.EXPOSURE = false;
  38006. _this.USEPHYSICALLIGHTFALLOFF = false;
  38007. _this.TWOSIDEDLIGHTING = false;
  38008. _this.SHADOWFLOAT = false;
  38009. _this.CLIPPLANE = false;
  38010. _this.POINTSIZE = false;
  38011. _this.FOG = false;
  38012. _this.LOGARITHMICDEPTH = false;
  38013. _this.FORCENORMALFORWARD = false;
  38014. _this.rebuild();
  38015. return _this;
  38016. }
  38017. PBRMaterialDefines.prototype.reset = function () {
  38018. _super.prototype.reset.call(this);
  38019. this.ALPHATESTVALUE = 0.5;
  38020. this.PBR = true;
  38021. };
  38022. return PBRMaterialDefines;
  38023. }(BABYLON.MaterialDefines));
  38024. /**
  38025. * The Physically based material base class of BJS.
  38026. *
  38027. * This offers the main features of a standard PBR material.
  38028. * For more information, please refer to the documentation :
  38029. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  38030. */
  38031. var PBRBaseMaterial = /** @class */ (function (_super) {
  38032. __extends(PBRBaseMaterial, _super);
  38033. /**
  38034. * Instantiates a new PBRMaterial instance.
  38035. *
  38036. * @param name The material name
  38037. * @param scene The scene the material will be use in.
  38038. */
  38039. function PBRBaseMaterial(name, scene) {
  38040. var _this = _super.call(this, name, scene) || this;
  38041. /**
  38042. * Intensity of the direct lights e.g. the four lights available in your scene.
  38043. * This impacts both the direct diffuse and specular highlights.
  38044. */
  38045. _this._directIntensity = 1.0;
  38046. /**
  38047. * Intensity of the emissive part of the material.
  38048. * This helps controlling the emissive effect without modifying the emissive color.
  38049. */
  38050. _this._emissiveIntensity = 1.0;
  38051. /**
  38052. * Intensity of the environment e.g. how much the environment will light the object
  38053. * either through harmonics for rough material or through the refelction for shiny ones.
  38054. */
  38055. _this._environmentIntensity = 1.0;
  38056. /**
  38057. * This is a special control allowing the reduction of the specular highlights coming from the
  38058. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  38059. */
  38060. _this._specularIntensity = 1.0;
  38061. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  38062. /**
  38063. * Debug Control allowing disabling the bump map on this material.
  38064. */
  38065. _this._disableBumpMap = false;
  38066. /**
  38067. * AKA Occlusion Texture Intensity in other nomenclature.
  38068. */
  38069. _this._ambientTextureStrength = 1.0;
  38070. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  38071. /**
  38072. * AKA Diffuse Color in other nomenclature.
  38073. */
  38074. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  38075. /**
  38076. * AKA Specular Color in other nomenclature.
  38077. */
  38078. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  38079. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  38080. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  38081. /**
  38082. * AKA Glossiness in other nomenclature.
  38083. */
  38084. _this._microSurface = 0.9;
  38085. /**
  38086. * source material index of refraction (IOR)' / 'destination material IOR.
  38087. */
  38088. _this._indexOfRefraction = 0.66;
  38089. /**
  38090. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  38091. */
  38092. _this._invertRefractionY = false;
  38093. /**
  38094. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  38095. * Materials half opaque for instance using refraction could benefit from this control.
  38096. */
  38097. _this._linkRefractionWithTransparency = false;
  38098. _this._useLightmapAsShadowmap = false;
  38099. /**
  38100. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  38101. * makes the reflect vector face the model (under horizon).
  38102. */
  38103. _this._useHorizonOcclusion = true;
  38104. /**
  38105. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  38106. * too much the area relying on ambient texture to define their ambient occlusion.
  38107. */
  38108. _this._useRadianceOcclusion = true;
  38109. /**
  38110. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  38111. */
  38112. _this._useAlphaFromAlbedoTexture = false;
  38113. /**
  38114. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  38115. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  38116. */
  38117. _this._useSpecularOverAlpha = true;
  38118. /**
  38119. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  38120. */
  38121. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  38122. /**
  38123. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  38124. */
  38125. _this._useRoughnessFromMetallicTextureAlpha = true;
  38126. /**
  38127. * Specifies if the metallic texture contains the roughness information in its green channel.
  38128. */
  38129. _this._useRoughnessFromMetallicTextureGreen = false;
  38130. /**
  38131. * Specifies if the metallic texture contains the metallness information in its blue channel.
  38132. */
  38133. _this._useMetallnessFromMetallicTextureBlue = false;
  38134. /**
  38135. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  38136. */
  38137. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  38138. /**
  38139. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  38140. */
  38141. _this._useAmbientInGrayScale = false;
  38142. /**
  38143. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  38144. * The material will try to infer what glossiness each pixel should be.
  38145. */
  38146. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  38147. /**
  38148. * BJS is using an harcoded light falloff based on a manually sets up range.
  38149. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  38150. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  38151. */
  38152. _this._usePhysicalLightFalloff = true;
  38153. /**
  38154. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  38155. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  38156. */
  38157. _this._useRadianceOverAlpha = true;
  38158. /**
  38159. * Allows using the bump map in parallax mode.
  38160. */
  38161. _this._useParallax = false;
  38162. /**
  38163. * Allows using the bump map in parallax occlusion mode.
  38164. */
  38165. _this._useParallaxOcclusion = false;
  38166. /**
  38167. * Controls the scale bias of the parallax mode.
  38168. */
  38169. _this._parallaxScaleBias = 0.05;
  38170. /**
  38171. * If sets to true, disables all the lights affecting the material.
  38172. */
  38173. _this._disableLighting = false;
  38174. /**
  38175. * Number of Simultaneous lights allowed on the material.
  38176. */
  38177. _this._maxSimultaneousLights = 4;
  38178. /**
  38179. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  38180. */
  38181. _this._invertNormalMapX = false;
  38182. /**
  38183. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  38184. */
  38185. _this._invertNormalMapY = false;
  38186. /**
  38187. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38188. */
  38189. _this._twoSidedLighting = false;
  38190. /**
  38191. * Defines the alpha limits in alpha test mode.
  38192. */
  38193. _this._alphaCutOff = 0.4;
  38194. /**
  38195. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  38196. */
  38197. _this._forceAlphaTest = false;
  38198. /**
  38199. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  38200. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  38201. */
  38202. _this._useAlphaFresnel = false;
  38203. /**
  38204. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  38205. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  38206. */
  38207. _this._useLinearAlphaFresnel = false;
  38208. /**
  38209. * The transparency mode of the material.
  38210. */
  38211. _this._transparencyMode = null;
  38212. /**
  38213. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  38214. * from cos thetav and roughness:
  38215. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  38216. */
  38217. _this._environmentBRDFTexture = null;
  38218. /**
  38219. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  38220. */
  38221. _this._forceIrradianceInFragment = false;
  38222. /**
  38223. * Force normal to face away from face.
  38224. */
  38225. _this._forceNormalForward = false;
  38226. /**
  38227. * Force metallic workflow.
  38228. */
  38229. _this._forceMetallicWorkflow = false;
  38230. _this._renderTargets = new BABYLON.SmartArray(16);
  38231. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  38232. // Setup the default processing configuration to the scene.
  38233. _this._attachImageProcessingConfiguration(null);
  38234. _this.getRenderTargetTextures = function () {
  38235. _this._renderTargets.reset();
  38236. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  38237. _this._renderTargets.push(_this._reflectionTexture);
  38238. }
  38239. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  38240. _this._renderTargets.push(_this._refractionTexture);
  38241. }
  38242. return _this._renderTargets;
  38243. };
  38244. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  38245. return _this;
  38246. }
  38247. /**
  38248. * Attaches a new image processing configuration to the PBR Material.
  38249. * @param configuration
  38250. */
  38251. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  38252. var _this = this;
  38253. if (configuration === this._imageProcessingConfiguration) {
  38254. return;
  38255. }
  38256. // Detaches observer.
  38257. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  38258. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  38259. }
  38260. // Pick the scene configuration if needed.
  38261. if (!configuration) {
  38262. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  38263. }
  38264. else {
  38265. this._imageProcessingConfiguration = configuration;
  38266. }
  38267. // Attaches observer.
  38268. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  38269. _this._markAllSubMeshesAsImageProcessingDirty();
  38270. });
  38271. };
  38272. PBRBaseMaterial.prototype.getClassName = function () {
  38273. return "PBRBaseMaterial";
  38274. };
  38275. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  38276. get: function () {
  38277. return this._useLogarithmicDepth;
  38278. },
  38279. set: function (value) {
  38280. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  38281. },
  38282. enumerable: true,
  38283. configurable: true
  38284. });
  38285. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  38286. /**
  38287. * Gets the current transparency mode.
  38288. */
  38289. get: function () {
  38290. return this._transparencyMode;
  38291. },
  38292. /**
  38293. * Sets the transparency mode of the material.
  38294. */
  38295. set: function (value) {
  38296. if (this._transparencyMode === value) {
  38297. return;
  38298. }
  38299. this._transparencyMode = value;
  38300. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  38301. this._markAllSubMeshesAsTexturesAndMiscDirty();
  38302. },
  38303. enumerable: true,
  38304. configurable: true
  38305. });
  38306. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  38307. /**
  38308. * Returns true if alpha blending should be disabled.
  38309. */
  38310. get: function () {
  38311. return (this._linkRefractionWithTransparency ||
  38312. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  38313. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  38314. },
  38315. enumerable: true,
  38316. configurable: true
  38317. });
  38318. /**
  38319. * Specifies whether or not this material should be rendered in alpha blend mode.
  38320. */
  38321. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  38322. if (this._disableAlphaBlending) {
  38323. return false;
  38324. }
  38325. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  38326. };
  38327. /**
  38328. * Specifies whether or not this material should be rendered in alpha blend mode for the given mesh.
  38329. */
  38330. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  38331. if (this._disableAlphaBlending) {
  38332. return false;
  38333. }
  38334. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  38335. };
  38336. /**
  38337. * Specifies whether or not this material should be rendered in alpha test mode.
  38338. */
  38339. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  38340. if (this._forceAlphaTest) {
  38341. return true;
  38342. }
  38343. if (this._linkRefractionWithTransparency) {
  38344. return false;
  38345. }
  38346. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  38347. };
  38348. /**
  38349. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  38350. */
  38351. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  38352. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  38353. };
  38354. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  38355. return this._albedoTexture;
  38356. };
  38357. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  38358. var _this = this;
  38359. if (subMesh.effect && this.isFrozen) {
  38360. if (this._wasPreviouslyReady) {
  38361. return true;
  38362. }
  38363. }
  38364. if (!subMesh._materialDefines) {
  38365. subMesh._materialDefines = new PBRMaterialDefines();
  38366. }
  38367. var scene = this.getScene();
  38368. var defines = subMesh._materialDefines;
  38369. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  38370. if (defines._renderId === scene.getRenderId()) {
  38371. return true;
  38372. }
  38373. }
  38374. var engine = scene.getEngine();
  38375. // Lights
  38376. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  38377. defines._needNormals = true;
  38378. // Textures
  38379. if (defines._areTexturesDirty) {
  38380. defines._needUVs = false;
  38381. if (scene.texturesEnabled) {
  38382. if (scene.getEngine().getCaps().textureLOD) {
  38383. defines.LODBASEDMICROSFURACE = true;
  38384. }
  38385. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  38386. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  38387. return false;
  38388. }
  38389. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  38390. }
  38391. else {
  38392. defines.ALBEDO = false;
  38393. }
  38394. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  38395. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  38396. return false;
  38397. }
  38398. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  38399. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  38400. }
  38401. else {
  38402. defines.AMBIENT = false;
  38403. }
  38404. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  38405. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  38406. return false;
  38407. }
  38408. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  38409. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  38410. }
  38411. else {
  38412. defines.OPACITY = false;
  38413. }
  38414. var reflectionTexture = this._getReflectionTexture();
  38415. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  38416. if (!reflectionTexture.isReadyOrNotBlocking()) {
  38417. return false;
  38418. }
  38419. defines.REFLECTION = true;
  38420. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  38421. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  38422. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  38423. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  38424. defines.INVERTCUBICMAP = true;
  38425. }
  38426. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  38427. switch (reflectionTexture.coordinatesMode) {
  38428. case BABYLON.Texture.CUBIC_MODE:
  38429. case BABYLON.Texture.INVCUBIC_MODE:
  38430. defines.REFLECTIONMAP_CUBIC = true;
  38431. break;
  38432. case BABYLON.Texture.EXPLICIT_MODE:
  38433. defines.REFLECTIONMAP_EXPLICIT = true;
  38434. break;
  38435. case BABYLON.Texture.PLANAR_MODE:
  38436. defines.REFLECTIONMAP_PLANAR = true;
  38437. break;
  38438. case BABYLON.Texture.PROJECTION_MODE:
  38439. defines.REFLECTIONMAP_PROJECTION = true;
  38440. break;
  38441. case BABYLON.Texture.SKYBOX_MODE:
  38442. defines.REFLECTIONMAP_SKYBOX = true;
  38443. break;
  38444. case BABYLON.Texture.SPHERICAL_MODE:
  38445. defines.REFLECTIONMAP_SPHERICAL = true;
  38446. break;
  38447. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  38448. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  38449. break;
  38450. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  38451. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  38452. break;
  38453. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  38454. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  38455. break;
  38456. }
  38457. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  38458. if (reflectionTexture.sphericalPolynomial) {
  38459. defines.USESPHERICALFROMREFLECTIONMAP = true;
  38460. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  38461. defines.USESPHERICALINVERTEX = false;
  38462. }
  38463. else {
  38464. defines.USESPHERICALINVERTEX = true;
  38465. }
  38466. }
  38467. }
  38468. }
  38469. else {
  38470. defines.REFLECTION = false;
  38471. defines.REFLECTIONMAP_3D = false;
  38472. defines.REFLECTIONMAP_SPHERICAL = false;
  38473. defines.REFLECTIONMAP_PLANAR = false;
  38474. defines.REFLECTIONMAP_CUBIC = false;
  38475. defines.REFLECTIONMAP_PROJECTION = false;
  38476. defines.REFLECTIONMAP_SKYBOX = false;
  38477. defines.REFLECTIONMAP_EXPLICIT = false;
  38478. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  38479. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  38480. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  38481. defines.INVERTCUBICMAP = false;
  38482. defines.USESPHERICALFROMREFLECTIONMAP = false;
  38483. defines.USESPHERICALINVERTEX = false;
  38484. defines.REFLECTIONMAP_OPPOSITEZ = false;
  38485. defines.LODINREFLECTIONALPHA = false;
  38486. defines.GAMMAREFLECTION = false;
  38487. }
  38488. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  38489. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  38490. return false;
  38491. }
  38492. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  38493. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  38494. }
  38495. else {
  38496. defines.LIGHTMAP = false;
  38497. }
  38498. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  38499. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  38500. return false;
  38501. }
  38502. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  38503. }
  38504. else {
  38505. defines.EMISSIVE = false;
  38506. }
  38507. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  38508. if (this._metallicTexture) {
  38509. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  38510. return false;
  38511. }
  38512. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  38513. defines.METALLICWORKFLOW = true;
  38514. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  38515. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  38516. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  38517. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  38518. }
  38519. else if (this._reflectivityTexture) {
  38520. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  38521. return false;
  38522. }
  38523. defines.METALLICWORKFLOW = false;
  38524. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  38525. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  38526. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  38527. }
  38528. else {
  38529. defines.METALLICWORKFLOW = false;
  38530. defines.REFLECTIVITY = false;
  38531. }
  38532. if (this._microSurfaceTexture) {
  38533. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  38534. return false;
  38535. }
  38536. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  38537. }
  38538. else {
  38539. defines.MICROSURFACEMAP = false;
  38540. }
  38541. }
  38542. else {
  38543. defines.REFLECTIVITY = false;
  38544. defines.MICROSURFACEMAP = false;
  38545. }
  38546. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  38547. // Bump texure can not be none blocking.
  38548. if (!this._bumpTexture.isReady()) {
  38549. return false;
  38550. }
  38551. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  38552. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  38553. defines.PARALLAX = true;
  38554. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  38555. }
  38556. else {
  38557. defines.PARALLAX = false;
  38558. }
  38559. }
  38560. else {
  38561. defines.BUMP = false;
  38562. }
  38563. var refractionTexture = this._getRefractionTexture();
  38564. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  38565. if (!refractionTexture.isReadyOrNotBlocking()) {
  38566. return false;
  38567. }
  38568. defines.REFRACTION = true;
  38569. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  38570. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  38571. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  38572. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  38573. if (this._linkRefractionWithTransparency) {
  38574. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  38575. }
  38576. }
  38577. else {
  38578. defines.REFRACTION = false;
  38579. }
  38580. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  38581. // This is blocking.
  38582. if (!this._environmentBRDFTexture.isReady()) {
  38583. return false;
  38584. }
  38585. defines.ENVIRONMENTBRDF = true;
  38586. }
  38587. else {
  38588. defines.ENVIRONMENTBRDF = false;
  38589. }
  38590. if (this._shouldUseAlphaFromAlbedoTexture()) {
  38591. defines.ALPHAFROMALBEDO = true;
  38592. }
  38593. else {
  38594. defines.ALPHAFROMALBEDO = false;
  38595. }
  38596. }
  38597. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  38598. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  38599. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  38600. if (this._forceMetallicWorkflow || (this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  38601. defines.METALLICWORKFLOW = true;
  38602. }
  38603. else {
  38604. defines.METALLICWORKFLOW = false;
  38605. }
  38606. if (!this.backFaceCulling && this._twoSidedLighting) {
  38607. defines.TWOSIDEDLIGHTING = true;
  38608. }
  38609. else {
  38610. defines.TWOSIDEDLIGHTING = false;
  38611. }
  38612. defines.ALPHATESTVALUE = this._alphaCutOff;
  38613. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  38614. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  38615. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  38616. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  38617. }
  38618. if (defines._areImageProcessingDirty) {
  38619. if (!this._imageProcessingConfiguration.isReady()) {
  38620. return false;
  38621. }
  38622. this._imageProcessingConfiguration.prepareDefines(defines);
  38623. }
  38624. defines.FORCENORMALFORWARD = this._forceNormalForward;
  38625. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  38626. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  38627. // Misc.
  38628. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  38629. // Values that need to be evaluated on every frame
  38630. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false);
  38631. // Attribs
  38632. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE) && mesh) {
  38633. var bufferMesh = null;
  38634. if (mesh instanceof BABYLON.InstancedMesh) {
  38635. bufferMesh = mesh.sourceMesh;
  38636. }
  38637. else if (mesh instanceof BABYLON.Mesh) {
  38638. bufferMesh = mesh;
  38639. }
  38640. if (bufferMesh) {
  38641. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  38642. // If the first normal's components is the zero vector in one of the submeshes, we have invalid normals
  38643. var normalVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.NormalKind);
  38644. var normals = normalVertexBuffer.getData();
  38645. var vertexBufferOffset = normalVertexBuffer.getOffset();
  38646. var strideSize = normalVertexBuffer.getStrideSize();
  38647. var offset = vertexBufferOffset + subMesh.indexStart * strideSize;
  38648. if (normals[offset] === 0 && normals[offset + 1] === 0 && normals[offset + 2] === 0) {
  38649. defines.NORMAL = false;
  38650. }
  38651. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38652. // If the first tangent's components is the zero vector in one of the submeshes, we have invalid tangents
  38653. var tangentVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.TangentKind);
  38654. var tangents = tangentVertexBuffer.getData();
  38655. var vertexBufferOffset_1 = tangentVertexBuffer.getOffset();
  38656. var strideSize_1 = tangentVertexBuffer.getStrideSize();
  38657. var offset_1 = vertexBufferOffset_1 + subMesh.indexStart * strideSize_1;
  38658. if (tangents[offset_1] === 0 && tangents[offset_1 + 1] === 0 && tangents[offset_1 + 2] === 0) {
  38659. defines.TANGENT = false;
  38660. }
  38661. }
  38662. }
  38663. else {
  38664. if (!scene.getEngine().getCaps().standardDerivatives) {
  38665. bufferMesh.createNormals(true);
  38666. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  38667. }
  38668. }
  38669. }
  38670. }
  38671. // Get correct effect
  38672. if (defines.isDirty) {
  38673. defines.markAsProcessed();
  38674. scene.resetCachedMaterial();
  38675. // Fallbacks
  38676. var fallbacks = new BABYLON.EffectFallbacks();
  38677. var fallbackRank = 0;
  38678. if (defines.USESPHERICALINVERTEX) {
  38679. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  38680. }
  38681. if (defines.FOG) {
  38682. fallbacks.addFallback(fallbackRank, "FOG");
  38683. }
  38684. if (defines.POINTSIZE) {
  38685. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  38686. }
  38687. if (defines.LOGARITHMICDEPTH) {
  38688. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  38689. }
  38690. if (defines.PARALLAX) {
  38691. fallbacks.addFallback(fallbackRank, "PARALLAX");
  38692. }
  38693. if (defines.PARALLAXOCCLUSION) {
  38694. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  38695. }
  38696. if (defines.ENVIRONMENTBRDF) {
  38697. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  38698. }
  38699. if (defines.TANGENT) {
  38700. fallbacks.addFallback(fallbackRank++, "TANGENT");
  38701. }
  38702. if (defines.BUMP) {
  38703. fallbacks.addFallback(fallbackRank++, "BUMP");
  38704. }
  38705. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  38706. if (defines.SPECULARTERM) {
  38707. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  38708. }
  38709. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  38710. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  38711. }
  38712. if (defines.LIGHTMAP) {
  38713. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  38714. }
  38715. if (defines.NORMAL) {
  38716. fallbacks.addFallback(fallbackRank++, "NORMAL");
  38717. }
  38718. if (defines.AMBIENT) {
  38719. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  38720. }
  38721. if (defines.EMISSIVE) {
  38722. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  38723. }
  38724. if (defines.VERTEXCOLOR) {
  38725. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  38726. }
  38727. if (defines.NUM_BONE_INFLUENCERS > 0) {
  38728. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  38729. }
  38730. if (defines.MORPHTARGETS) {
  38731. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  38732. }
  38733. //Attributes
  38734. var attribs = [BABYLON.VertexBuffer.PositionKind];
  38735. if (defines.NORMAL) {
  38736. attribs.push(BABYLON.VertexBuffer.NormalKind);
  38737. }
  38738. if (defines.TANGENT) {
  38739. attribs.push(BABYLON.VertexBuffer.TangentKind);
  38740. }
  38741. if (defines.UV1) {
  38742. attribs.push(BABYLON.VertexBuffer.UVKind);
  38743. }
  38744. if (defines.UV2) {
  38745. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  38746. }
  38747. if (defines.VERTEXCOLOR) {
  38748. attribs.push(BABYLON.VertexBuffer.ColorKind);
  38749. }
  38750. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  38751. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  38752. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  38753. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  38754. "vFogInfos", "vFogColor", "pointSize",
  38755. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  38756. "mBones",
  38757. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  38758. "vLightingIntensity",
  38759. "logarithmicDepthConstant",
  38760. "vSphericalX", "vSphericalY", "vSphericalZ",
  38761. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  38762. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  38763. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  38764. "vTangentSpaceParams"
  38765. ];
  38766. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  38767. "bumpSampler", "lightmapSampler", "opacitySampler",
  38768. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  38769. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  38770. "microSurfaceSampler", "environmentBrdfSampler"];
  38771. var uniformBuffers = ["Material", "Scene"];
  38772. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  38773. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  38774. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  38775. uniformsNames: uniforms,
  38776. uniformBuffersNames: uniformBuffers,
  38777. samplers: samplers,
  38778. defines: defines,
  38779. maxSimultaneousLights: this._maxSimultaneousLights
  38780. });
  38781. var onCompiled = function (effect) {
  38782. if (_this.onCompiled) {
  38783. _this.onCompiled(effect);
  38784. }
  38785. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  38786. };
  38787. var join = defines.toString();
  38788. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  38789. attributes: attribs,
  38790. uniformsNames: uniforms,
  38791. uniformBuffersNames: uniformBuffers,
  38792. samplers: samplers,
  38793. defines: join,
  38794. fallbacks: fallbacks,
  38795. onCompiled: onCompiled,
  38796. onError: this.onError,
  38797. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  38798. }, engine), defines);
  38799. this.buildUniformLayout();
  38800. }
  38801. if (!subMesh.effect || !subMesh.effect.isReady()) {
  38802. return false;
  38803. }
  38804. defines._renderId = scene.getRenderId();
  38805. this._wasPreviouslyReady = true;
  38806. return true;
  38807. };
  38808. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  38809. // Order is important !
  38810. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  38811. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  38812. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  38813. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  38814. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  38815. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  38816. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  38817. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  38818. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  38819. this._uniformBuffer.addUniform("vBumpInfos", 3);
  38820. this._uniformBuffer.addUniform("albedoMatrix", 16);
  38821. this._uniformBuffer.addUniform("ambientMatrix", 16);
  38822. this._uniformBuffer.addUniform("opacityMatrix", 16);
  38823. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  38824. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  38825. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  38826. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  38827. this._uniformBuffer.addUniform("bumpMatrix", 16);
  38828. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  38829. this._uniformBuffer.addUniform("refractionMatrix", 16);
  38830. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  38831. this._uniformBuffer.addUniform("vReflectionColor", 3);
  38832. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  38833. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  38834. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  38835. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  38836. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  38837. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  38838. this._uniformBuffer.addUniform("pointSize", 1);
  38839. this._uniformBuffer.create();
  38840. };
  38841. PBRBaseMaterial.prototype.unbind = function () {
  38842. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  38843. this._uniformBuffer.setTexture("reflectionSampler", null);
  38844. }
  38845. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  38846. this._uniformBuffer.setTexture("refractionSampler", null);
  38847. }
  38848. _super.prototype.unbind.call(this);
  38849. };
  38850. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  38851. this._activeEffect.setMatrix("world", world);
  38852. };
  38853. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  38854. var scene = this.getScene();
  38855. var defines = subMesh._materialDefines;
  38856. if (!defines) {
  38857. return;
  38858. }
  38859. var effect = subMesh.effect;
  38860. if (!effect) {
  38861. return;
  38862. }
  38863. this._activeEffect = effect;
  38864. // Matrices
  38865. this.bindOnlyWorldMatrix(world);
  38866. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  38867. // Bones
  38868. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  38869. var reflectionTexture = null;
  38870. if (mustRebind) {
  38871. this._uniformBuffer.bindToEffect(effect, "Material");
  38872. this.bindViewProjection(effect);
  38873. reflectionTexture = this._getReflectionTexture();
  38874. var refractionTexture = this._getRefractionTexture();
  38875. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  38876. // Texture uniforms
  38877. if (scene.texturesEnabled) {
  38878. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  38879. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  38880. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  38881. }
  38882. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  38883. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  38884. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  38885. }
  38886. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  38887. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  38888. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  38889. }
  38890. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  38891. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  38892. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  38893. var polynomials = reflectionTexture.sphericalPolynomial;
  38894. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  38895. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  38896. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  38897. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  38898. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  38899. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  38900. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  38901. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  38902. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  38903. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  38904. }
  38905. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  38906. }
  38907. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  38908. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  38909. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  38910. }
  38911. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  38912. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  38913. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  38914. }
  38915. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  38916. if (this._metallicTexture) {
  38917. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  38918. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  38919. }
  38920. else if (this._reflectivityTexture) {
  38921. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  38922. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  38923. }
  38924. if (this._microSurfaceTexture) {
  38925. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  38926. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  38927. }
  38928. }
  38929. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  38930. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  38931. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  38932. if (scene._mirroredCameraPosition) {
  38933. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  38934. }
  38935. else {
  38936. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  38937. }
  38938. }
  38939. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  38940. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  38941. var depth = 1.0;
  38942. if (!refractionTexture.isCube) {
  38943. if (refractionTexture.depth) {
  38944. depth = refractionTexture.depth;
  38945. }
  38946. }
  38947. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  38948. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  38949. }
  38950. }
  38951. // Point size
  38952. if (this.pointsCloud) {
  38953. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  38954. }
  38955. // Colors
  38956. if (defines.METALLICWORKFLOW) {
  38957. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  38958. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  38959. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  38960. }
  38961. else {
  38962. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  38963. }
  38964. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  38965. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  38966. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  38967. // Misc
  38968. this._lightingInfos.x = this._directIntensity;
  38969. this._lightingInfos.y = this._emissiveIntensity;
  38970. this._lightingInfos.z = this._environmentIntensity;
  38971. this._lightingInfos.w = this._specularIntensity;
  38972. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  38973. }
  38974. // Textures
  38975. if (scene.texturesEnabled) {
  38976. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  38977. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  38978. }
  38979. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  38980. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  38981. }
  38982. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  38983. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  38984. }
  38985. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  38986. if (defines.LODBASEDMICROSFURACE) {
  38987. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  38988. }
  38989. else {
  38990. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  38991. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  38992. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  38993. }
  38994. }
  38995. if (defines.ENVIRONMENTBRDF) {
  38996. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  38997. }
  38998. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  38999. if (defines.LODBASEDMICROSFURACE) {
  39000. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  39001. }
  39002. else {
  39003. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  39004. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  39005. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  39006. }
  39007. }
  39008. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  39009. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  39010. }
  39011. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  39012. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  39013. }
  39014. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  39015. if (this._metallicTexture) {
  39016. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  39017. }
  39018. else if (this._reflectivityTexture) {
  39019. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  39020. }
  39021. if (this._microSurfaceTexture) {
  39022. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  39023. }
  39024. }
  39025. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  39026. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  39027. }
  39028. }
  39029. // Clip plane
  39030. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  39031. // Colors
  39032. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  39033. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  39034. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  39035. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  39036. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  39037. }
  39038. if (mustRebind || !this.isFrozen) {
  39039. // Lights
  39040. if (scene.lightsEnabled && !this._disableLighting) {
  39041. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  39042. }
  39043. // View
  39044. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  39045. this.bindView(effect);
  39046. }
  39047. // Fog
  39048. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  39049. // Morph targets
  39050. if (defines.NUM_MORPH_INFLUENCERS) {
  39051. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  39052. }
  39053. // image processing
  39054. this._imageProcessingConfiguration.bind(this._activeEffect);
  39055. // Log. depth
  39056. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  39057. }
  39058. this._uniformBuffer.update();
  39059. this._afterBind(mesh);
  39060. };
  39061. PBRBaseMaterial.prototype.getAnimatables = function () {
  39062. var results = [];
  39063. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  39064. results.push(this._albedoTexture);
  39065. }
  39066. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  39067. results.push(this._ambientTexture);
  39068. }
  39069. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  39070. results.push(this._opacityTexture);
  39071. }
  39072. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  39073. results.push(this._reflectionTexture);
  39074. }
  39075. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  39076. results.push(this._emissiveTexture);
  39077. }
  39078. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  39079. results.push(this._metallicTexture);
  39080. }
  39081. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  39082. results.push(this._reflectivityTexture);
  39083. }
  39084. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  39085. results.push(this._bumpTexture);
  39086. }
  39087. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  39088. results.push(this._lightmapTexture);
  39089. }
  39090. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  39091. results.push(this._refractionTexture);
  39092. }
  39093. return results;
  39094. };
  39095. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  39096. if (this._reflectionTexture) {
  39097. return this._reflectionTexture;
  39098. }
  39099. return this.getScene().environmentTexture;
  39100. };
  39101. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  39102. if (this._refractionTexture) {
  39103. return this._refractionTexture;
  39104. }
  39105. if (this._linkRefractionWithTransparency) {
  39106. return this.getScene().environmentTexture;
  39107. }
  39108. return null;
  39109. };
  39110. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  39111. if (forceDisposeTextures) {
  39112. if (this._albedoTexture) {
  39113. this._albedoTexture.dispose();
  39114. }
  39115. if (this._ambientTexture) {
  39116. this._ambientTexture.dispose();
  39117. }
  39118. if (this._opacityTexture) {
  39119. this._opacityTexture.dispose();
  39120. }
  39121. if (this._reflectionTexture) {
  39122. this._reflectionTexture.dispose();
  39123. }
  39124. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  39125. this._environmentBRDFTexture.dispose();
  39126. }
  39127. if (this._emissiveTexture) {
  39128. this._emissiveTexture.dispose();
  39129. }
  39130. if (this._metallicTexture) {
  39131. this._metallicTexture.dispose();
  39132. }
  39133. if (this._reflectivityTexture) {
  39134. this._reflectivityTexture.dispose();
  39135. }
  39136. if (this._bumpTexture) {
  39137. this._bumpTexture.dispose();
  39138. }
  39139. if (this._lightmapTexture) {
  39140. this._lightmapTexture.dispose();
  39141. }
  39142. if (this._refractionTexture) {
  39143. this._refractionTexture.dispose();
  39144. }
  39145. }
  39146. this._renderTargets.dispose();
  39147. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39148. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39149. }
  39150. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  39151. };
  39152. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  39153. __decorate([
  39154. BABYLON.serializeAsImageProcessingConfiguration()
  39155. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  39156. __decorate([
  39157. BABYLON.serialize()
  39158. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  39159. __decorate([
  39160. BABYLON.serialize()
  39161. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  39162. return PBRBaseMaterial;
  39163. }(BABYLON.PushMaterial));
  39164. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  39165. })(BABYLON || (BABYLON = {}));
  39166. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  39167. var BABYLON;
  39168. (function (BABYLON) {
  39169. /**
  39170. * The Physically based simple base material of BJS.
  39171. *
  39172. * This enables better naming and convention enforcements on top of the pbrMaterial.
  39173. * It is used as the base class for both the specGloss and metalRough conventions.
  39174. */
  39175. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  39176. __extends(PBRBaseSimpleMaterial, _super);
  39177. /**
  39178. * Instantiates a new PBRMaterial instance.
  39179. *
  39180. * @param name The material name
  39181. * @param scene The scene the material will be use in.
  39182. */
  39183. function PBRBaseSimpleMaterial(name, scene) {
  39184. var _this = _super.call(this, name, scene) || this;
  39185. /**
  39186. * Number of Simultaneous lights allowed on the material.
  39187. */
  39188. _this.maxSimultaneousLights = 4;
  39189. /**
  39190. * If sets to true, disables all the lights affecting the material.
  39191. */
  39192. _this.disableLighting = false;
  39193. /**
  39194. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  39195. */
  39196. _this.invertNormalMapX = false;
  39197. /**
  39198. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  39199. */
  39200. _this.invertNormalMapY = false;
  39201. /**
  39202. * Emissivie color used to self-illuminate the model.
  39203. */
  39204. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  39205. /**
  39206. * Occlusion Channel Strenght.
  39207. */
  39208. _this.occlusionStrength = 1.0;
  39209. _this.useLightmapAsShadowmap = false;
  39210. _this._useAlphaFromAlbedoTexture = true;
  39211. _this._useAmbientInGrayScale = true;
  39212. return _this;
  39213. }
  39214. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  39215. /**
  39216. * Gets the current double sided mode.
  39217. */
  39218. get: function () {
  39219. return this._twoSidedLighting;
  39220. },
  39221. /**
  39222. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39223. */
  39224. set: function (value) {
  39225. if (this._twoSidedLighting === value) {
  39226. return;
  39227. }
  39228. this._twoSidedLighting = value;
  39229. this.backFaceCulling = !value;
  39230. this._markAllSubMeshesAsTexturesDirty();
  39231. },
  39232. enumerable: true,
  39233. configurable: true
  39234. });
  39235. /**
  39236. * Return the active textures of the material.
  39237. */
  39238. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  39239. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39240. if (this.environmentTexture) {
  39241. activeTextures.push(this.environmentTexture);
  39242. }
  39243. if (this.normalTexture) {
  39244. activeTextures.push(this.normalTexture);
  39245. }
  39246. if (this.emissiveTexture) {
  39247. activeTextures.push(this.emissiveTexture);
  39248. }
  39249. if (this.occlusionTexture) {
  39250. activeTextures.push(this.occlusionTexture);
  39251. }
  39252. if (this.lightmapTexture) {
  39253. activeTextures.push(this.lightmapTexture);
  39254. }
  39255. return activeTextures;
  39256. };
  39257. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  39258. if (_super.prototype.hasTexture.call(this, texture)) {
  39259. return true;
  39260. }
  39261. if (this.lightmapTexture === texture) {
  39262. return true;
  39263. }
  39264. return false;
  39265. };
  39266. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  39267. return "PBRBaseSimpleMaterial";
  39268. };
  39269. __decorate([
  39270. BABYLON.serialize(),
  39271. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39272. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  39273. __decorate([
  39274. BABYLON.serialize(),
  39275. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39276. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  39277. __decorate([
  39278. BABYLON.serializeAsTexture(),
  39279. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  39280. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  39281. __decorate([
  39282. BABYLON.serialize(),
  39283. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39284. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  39285. __decorate([
  39286. BABYLON.serialize(),
  39287. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39288. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  39289. __decorate([
  39290. BABYLON.serializeAsTexture(),
  39291. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  39292. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  39293. __decorate([
  39294. BABYLON.serializeAsColor3("emissive"),
  39295. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39296. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  39297. __decorate([
  39298. BABYLON.serializeAsTexture(),
  39299. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39300. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  39301. __decorate([
  39302. BABYLON.serialize(),
  39303. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  39304. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  39305. __decorate([
  39306. BABYLON.serializeAsTexture(),
  39307. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  39308. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  39309. __decorate([
  39310. BABYLON.serialize(),
  39311. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  39312. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  39313. __decorate([
  39314. BABYLON.serialize()
  39315. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  39316. __decorate([
  39317. BABYLON.serializeAsTexture(),
  39318. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  39319. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  39320. __decorate([
  39321. BABYLON.serialize(),
  39322. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39323. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  39324. return PBRBaseSimpleMaterial;
  39325. }(BABYLON.PBRBaseMaterial));
  39326. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  39327. })(BABYLON || (BABYLON = {}));
  39328. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  39329. var BABYLON;
  39330. (function (BABYLON) {
  39331. /**
  39332. * The Physically based material of BJS.
  39333. *
  39334. * This offers the main features of a standard PBR material.
  39335. * For more information, please refer to the documentation :
  39336. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  39337. */
  39338. var PBRMaterial = /** @class */ (function (_super) {
  39339. __extends(PBRMaterial, _super);
  39340. /**
  39341. * Instantiates a new PBRMaterial instance.
  39342. *
  39343. * @param name The material name
  39344. * @param scene The scene the material will be use in.
  39345. */
  39346. function PBRMaterial(name, scene) {
  39347. var _this = _super.call(this, name, scene) || this;
  39348. /**
  39349. * Intensity of the direct lights e.g. the four lights available in your scene.
  39350. * This impacts both the direct diffuse and specular highlights.
  39351. */
  39352. _this.directIntensity = 1.0;
  39353. /**
  39354. * Intensity of the emissive part of the material.
  39355. * This helps controlling the emissive effect without modifying the emissive color.
  39356. */
  39357. _this.emissiveIntensity = 1.0;
  39358. /**
  39359. * Intensity of the environment e.g. how much the environment will light the object
  39360. * either through harmonics for rough material or through the refelction for shiny ones.
  39361. */
  39362. _this.environmentIntensity = 1.0;
  39363. /**
  39364. * This is a special control allowing the reduction of the specular highlights coming from the
  39365. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  39366. */
  39367. _this.specularIntensity = 1.0;
  39368. /**
  39369. * Debug Control allowing disabling the bump map on this material.
  39370. */
  39371. _this.disableBumpMap = false;
  39372. /**
  39373. * AKA Occlusion Texture Intensity in other nomenclature.
  39374. */
  39375. _this.ambientTextureStrength = 1.0;
  39376. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  39377. /**
  39378. * AKA Diffuse Color in other nomenclature.
  39379. */
  39380. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  39381. /**
  39382. * AKA Specular Color in other nomenclature.
  39383. */
  39384. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  39385. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  39386. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  39387. /**
  39388. * AKA Glossiness in other nomenclature.
  39389. */
  39390. _this.microSurface = 1.0;
  39391. /**
  39392. * source material index of refraction (IOR)' / 'destination material IOR.
  39393. */
  39394. _this.indexOfRefraction = 0.66;
  39395. /**
  39396. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  39397. */
  39398. _this.invertRefractionY = false;
  39399. /**
  39400. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  39401. * Materials half opaque for instance using refraction could benefit from this control.
  39402. */
  39403. _this.linkRefractionWithTransparency = false;
  39404. _this.useLightmapAsShadowmap = false;
  39405. /**
  39406. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  39407. */
  39408. _this.useAlphaFromAlbedoTexture = false;
  39409. /**
  39410. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  39411. */
  39412. _this.forceAlphaTest = false;
  39413. /**
  39414. * Defines the alpha limits in alpha test mode.
  39415. */
  39416. _this.alphaCutOff = 0.4;
  39417. /**
  39418. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  39419. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  39420. */
  39421. _this.useSpecularOverAlpha = true;
  39422. /**
  39423. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  39424. */
  39425. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  39426. /**
  39427. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  39428. */
  39429. _this.useRoughnessFromMetallicTextureAlpha = true;
  39430. /**
  39431. * Specifies if the metallic texture contains the roughness information in its green channel.
  39432. */
  39433. _this.useRoughnessFromMetallicTextureGreen = false;
  39434. /**
  39435. * Specifies if the metallic texture contains the metallness information in its blue channel.
  39436. */
  39437. _this.useMetallnessFromMetallicTextureBlue = false;
  39438. /**
  39439. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  39440. */
  39441. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  39442. /**
  39443. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  39444. */
  39445. _this.useAmbientInGrayScale = false;
  39446. /**
  39447. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  39448. * The material will try to infer what glossiness each pixel should be.
  39449. */
  39450. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  39451. /**
  39452. * BJS is using an harcoded light falloff based on a manually sets up range.
  39453. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  39454. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  39455. */
  39456. _this.usePhysicalLightFalloff = true;
  39457. /**
  39458. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  39459. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  39460. */
  39461. _this.useRadianceOverAlpha = true;
  39462. /**
  39463. * Allows using the bump map in parallax mode.
  39464. */
  39465. _this.useParallax = false;
  39466. /**
  39467. * Allows using the bump map in parallax occlusion mode.
  39468. */
  39469. _this.useParallaxOcclusion = false;
  39470. /**
  39471. * Controls the scale bias of the parallax mode.
  39472. */
  39473. _this.parallaxScaleBias = 0.05;
  39474. /**
  39475. * If sets to true, disables all the lights affecting the material.
  39476. */
  39477. _this.disableLighting = false;
  39478. /**
  39479. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  39480. */
  39481. _this.forceIrradianceInFragment = false;
  39482. /**
  39483. * Number of Simultaneous lights allowed on the material.
  39484. */
  39485. _this.maxSimultaneousLights = 4;
  39486. /**
  39487. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  39488. */
  39489. _this.invertNormalMapX = false;
  39490. /**
  39491. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  39492. */
  39493. _this.invertNormalMapY = false;
  39494. /**
  39495. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39496. */
  39497. _this.twoSidedLighting = false;
  39498. /**
  39499. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  39500. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  39501. */
  39502. _this.useAlphaFresnel = false;
  39503. /**
  39504. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  39505. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  39506. */
  39507. _this.useLinearAlphaFresnel = false;
  39508. /**
  39509. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  39510. * And/Or occlude the blended part.
  39511. */
  39512. _this.environmentBRDFTexture = null;
  39513. /**
  39514. * Force normal to face away from face.
  39515. */
  39516. _this.forceNormalForward = false;
  39517. /**
  39518. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  39519. * makes the reflect vector face the model (under horizon).
  39520. */
  39521. _this.useHorizonOcclusion = true;
  39522. /**
  39523. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  39524. * too much the area relying on ambient texture to define their ambient occlusion.
  39525. */
  39526. _this.useRadianceOcclusion = true;
  39527. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  39528. return _this;
  39529. }
  39530. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  39531. /**
  39532. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  39533. */
  39534. get: function () {
  39535. return this._PBRMATERIAL_OPAQUE;
  39536. },
  39537. enumerable: true,
  39538. configurable: true
  39539. });
  39540. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  39541. /**
  39542. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  39543. */
  39544. get: function () {
  39545. return this._PBRMATERIAL_ALPHATEST;
  39546. },
  39547. enumerable: true,
  39548. configurable: true
  39549. });
  39550. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  39551. /**
  39552. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  39553. */
  39554. get: function () {
  39555. return this._PBRMATERIAL_ALPHABLEND;
  39556. },
  39557. enumerable: true,
  39558. configurable: true
  39559. });
  39560. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  39561. /**
  39562. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  39563. * They are also discarded below the alpha cutoff threshold to improve performances.
  39564. */
  39565. get: function () {
  39566. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  39567. },
  39568. enumerable: true,
  39569. configurable: true
  39570. });
  39571. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  39572. /**
  39573. * Gets the image processing configuration used either in this material.
  39574. */
  39575. get: function () {
  39576. return this._imageProcessingConfiguration;
  39577. },
  39578. /**
  39579. * Sets the Default image processing configuration used either in the this material.
  39580. *
  39581. * If sets to null, the scene one is in use.
  39582. */
  39583. set: function (value) {
  39584. this._attachImageProcessingConfiguration(value);
  39585. // Ensure the effect will be rebuilt.
  39586. this._markAllSubMeshesAsTexturesDirty();
  39587. },
  39588. enumerable: true,
  39589. configurable: true
  39590. });
  39591. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  39592. /**
  39593. * Gets wether the color curves effect is enabled.
  39594. */
  39595. get: function () {
  39596. return this.imageProcessingConfiguration.colorCurvesEnabled;
  39597. },
  39598. /**
  39599. * Sets wether the color curves effect is enabled.
  39600. */
  39601. set: function (value) {
  39602. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  39603. },
  39604. enumerable: true,
  39605. configurable: true
  39606. });
  39607. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  39608. /**
  39609. * Gets wether the color grading effect is enabled.
  39610. */
  39611. get: function () {
  39612. return this.imageProcessingConfiguration.colorGradingEnabled;
  39613. },
  39614. /**
  39615. * Gets wether the color grading effect is enabled.
  39616. */
  39617. set: function (value) {
  39618. this.imageProcessingConfiguration.colorGradingEnabled = value;
  39619. },
  39620. enumerable: true,
  39621. configurable: true
  39622. });
  39623. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  39624. /**
  39625. * Gets wether tonemapping is enabled or not.
  39626. */
  39627. get: function () {
  39628. return this._imageProcessingConfiguration.toneMappingEnabled;
  39629. },
  39630. /**
  39631. * Sets wether tonemapping is enabled or not
  39632. */
  39633. set: function (value) {
  39634. this._imageProcessingConfiguration.toneMappingEnabled = value;
  39635. },
  39636. enumerable: true,
  39637. configurable: true
  39638. });
  39639. ;
  39640. ;
  39641. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  39642. /**
  39643. * The camera exposure used on this material.
  39644. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39645. * This corresponds to a photographic exposure.
  39646. */
  39647. get: function () {
  39648. return this._imageProcessingConfiguration.exposure;
  39649. },
  39650. /**
  39651. * The camera exposure used on this material.
  39652. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39653. * This corresponds to a photographic exposure.
  39654. */
  39655. set: function (value) {
  39656. this._imageProcessingConfiguration.exposure = value;
  39657. },
  39658. enumerable: true,
  39659. configurable: true
  39660. });
  39661. ;
  39662. ;
  39663. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  39664. /**
  39665. * Gets The camera contrast used on this material.
  39666. */
  39667. get: function () {
  39668. return this._imageProcessingConfiguration.contrast;
  39669. },
  39670. /**
  39671. * Sets The camera contrast used on this material.
  39672. */
  39673. set: function (value) {
  39674. this._imageProcessingConfiguration.contrast = value;
  39675. },
  39676. enumerable: true,
  39677. configurable: true
  39678. });
  39679. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  39680. /**
  39681. * Gets the Color Grading 2D Lookup Texture.
  39682. */
  39683. get: function () {
  39684. return this._imageProcessingConfiguration.colorGradingTexture;
  39685. },
  39686. /**
  39687. * Sets the Color Grading 2D Lookup Texture.
  39688. */
  39689. set: function (value) {
  39690. this._imageProcessingConfiguration.colorGradingTexture = value;
  39691. },
  39692. enumerable: true,
  39693. configurable: true
  39694. });
  39695. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  39696. /**
  39697. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39698. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39699. * 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;
  39700. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39701. */
  39702. get: function () {
  39703. return this._imageProcessingConfiguration.colorCurves;
  39704. },
  39705. /**
  39706. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39707. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39708. * 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;
  39709. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39710. */
  39711. set: function (value) {
  39712. this._imageProcessingConfiguration.colorCurves = value;
  39713. },
  39714. enumerable: true,
  39715. configurable: true
  39716. });
  39717. PBRMaterial.prototype.getClassName = function () {
  39718. return "PBRMaterial";
  39719. };
  39720. PBRMaterial.prototype.getActiveTextures = function () {
  39721. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39722. if (this._albedoTexture) {
  39723. activeTextures.push(this._albedoTexture);
  39724. }
  39725. if (this._ambientTexture) {
  39726. activeTextures.push(this._ambientTexture);
  39727. }
  39728. if (this._opacityTexture) {
  39729. activeTextures.push(this._opacityTexture);
  39730. }
  39731. if (this._reflectionTexture) {
  39732. activeTextures.push(this._reflectionTexture);
  39733. }
  39734. if (this._emissiveTexture) {
  39735. activeTextures.push(this._emissiveTexture);
  39736. }
  39737. if (this._reflectivityTexture) {
  39738. activeTextures.push(this._reflectivityTexture);
  39739. }
  39740. if (this._metallicTexture) {
  39741. activeTextures.push(this._metallicTexture);
  39742. }
  39743. if (this._microSurfaceTexture) {
  39744. activeTextures.push(this._microSurfaceTexture);
  39745. }
  39746. if (this._bumpTexture) {
  39747. activeTextures.push(this._bumpTexture);
  39748. }
  39749. if (this._lightmapTexture) {
  39750. activeTextures.push(this._lightmapTexture);
  39751. }
  39752. if (this._refractionTexture) {
  39753. activeTextures.push(this._refractionTexture);
  39754. }
  39755. return activeTextures;
  39756. };
  39757. PBRMaterial.prototype.hasTexture = function (texture) {
  39758. if (_super.prototype.hasTexture.call(this, texture)) {
  39759. return true;
  39760. }
  39761. if (this._albedoTexture === texture) {
  39762. return true;
  39763. }
  39764. if (this._ambientTexture === texture) {
  39765. return true;
  39766. }
  39767. if (this._opacityTexture === texture) {
  39768. return true;
  39769. }
  39770. if (this._reflectionTexture === texture) {
  39771. return true;
  39772. }
  39773. if (this._reflectivityTexture === texture) {
  39774. return true;
  39775. }
  39776. if (this._metallicTexture === texture) {
  39777. return true;
  39778. }
  39779. if (this._microSurfaceTexture === texture) {
  39780. return true;
  39781. }
  39782. if (this._bumpTexture === texture) {
  39783. return true;
  39784. }
  39785. if (this._lightmapTexture === texture) {
  39786. return true;
  39787. }
  39788. if (this._refractionTexture === texture) {
  39789. return true;
  39790. }
  39791. return false;
  39792. };
  39793. PBRMaterial.prototype.clone = function (name) {
  39794. var _this = this;
  39795. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  39796. clone.id = name;
  39797. clone.name = name;
  39798. return clone;
  39799. };
  39800. PBRMaterial.prototype.serialize = function () {
  39801. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  39802. serializationObject.customType = "BABYLON.PBRMaterial";
  39803. return serializationObject;
  39804. };
  39805. // Statics
  39806. PBRMaterial.Parse = function (source, scene, rootUrl) {
  39807. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  39808. };
  39809. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  39810. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  39811. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  39812. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  39813. __decorate([
  39814. BABYLON.serialize(),
  39815. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39816. ], PBRMaterial.prototype, "directIntensity", void 0);
  39817. __decorate([
  39818. BABYLON.serialize(),
  39819. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39820. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  39821. __decorate([
  39822. BABYLON.serialize(),
  39823. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39824. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  39825. __decorate([
  39826. BABYLON.serialize(),
  39827. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39828. ], PBRMaterial.prototype, "specularIntensity", void 0);
  39829. __decorate([
  39830. BABYLON.serialize(),
  39831. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39832. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  39833. __decorate([
  39834. BABYLON.serializeAsTexture(),
  39835. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39836. ], PBRMaterial.prototype, "albedoTexture", void 0);
  39837. __decorate([
  39838. BABYLON.serializeAsTexture(),
  39839. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39840. ], PBRMaterial.prototype, "ambientTexture", void 0);
  39841. __decorate([
  39842. BABYLON.serialize(),
  39843. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39844. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  39845. __decorate([
  39846. BABYLON.serializeAsTexture(),
  39847. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  39848. ], PBRMaterial.prototype, "opacityTexture", void 0);
  39849. __decorate([
  39850. BABYLON.serializeAsTexture(),
  39851. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39852. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  39853. __decorate([
  39854. BABYLON.serializeAsTexture(),
  39855. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39856. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  39857. __decorate([
  39858. BABYLON.serializeAsTexture(),
  39859. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39860. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  39861. __decorate([
  39862. BABYLON.serializeAsTexture(),
  39863. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39864. ], PBRMaterial.prototype, "metallicTexture", void 0);
  39865. __decorate([
  39866. BABYLON.serialize(),
  39867. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39868. ], PBRMaterial.prototype, "metallic", void 0);
  39869. __decorate([
  39870. BABYLON.serialize(),
  39871. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39872. ], PBRMaterial.prototype, "roughness", void 0);
  39873. __decorate([
  39874. BABYLON.serializeAsTexture(),
  39875. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39876. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  39877. __decorate([
  39878. BABYLON.serializeAsTexture(),
  39879. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39880. ], PBRMaterial.prototype, "bumpTexture", void 0);
  39881. __decorate([
  39882. BABYLON.serializeAsTexture(),
  39883. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  39884. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  39885. __decorate([
  39886. BABYLON.serializeAsTexture(),
  39887. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39888. ], PBRMaterial.prototype, "refractionTexture", void 0);
  39889. __decorate([
  39890. BABYLON.serializeAsColor3("ambient"),
  39891. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39892. ], PBRMaterial.prototype, "ambientColor", void 0);
  39893. __decorate([
  39894. BABYLON.serializeAsColor3("albedo"),
  39895. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39896. ], PBRMaterial.prototype, "albedoColor", void 0);
  39897. __decorate([
  39898. BABYLON.serializeAsColor3("reflectivity"),
  39899. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39900. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  39901. __decorate([
  39902. BABYLON.serializeAsColor3("reflection"),
  39903. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39904. ], PBRMaterial.prototype, "reflectionColor", void 0);
  39905. __decorate([
  39906. BABYLON.serializeAsColor3("emissive"),
  39907. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39908. ], PBRMaterial.prototype, "emissiveColor", void 0);
  39909. __decorate([
  39910. BABYLON.serialize(),
  39911. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39912. ], PBRMaterial.prototype, "microSurface", void 0);
  39913. __decorate([
  39914. BABYLON.serialize(),
  39915. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39916. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  39917. __decorate([
  39918. BABYLON.serialize(),
  39919. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39920. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  39921. __decorate([
  39922. BABYLON.serialize(),
  39923. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39924. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  39925. __decorate([
  39926. BABYLON.serialize(),
  39927. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39928. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  39929. __decorate([
  39930. BABYLON.serialize(),
  39931. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  39932. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  39933. __decorate([
  39934. BABYLON.serialize(),
  39935. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  39936. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  39937. __decorate([
  39938. BABYLON.serialize(),
  39939. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  39940. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  39941. __decorate([
  39942. BABYLON.serialize(),
  39943. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39944. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  39945. __decorate([
  39946. BABYLON.serialize(),
  39947. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39948. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  39949. __decorate([
  39950. BABYLON.serialize(),
  39951. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39952. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  39953. __decorate([
  39954. BABYLON.serialize(),
  39955. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39956. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  39957. __decorate([
  39958. BABYLON.serialize(),
  39959. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39960. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  39961. __decorate([
  39962. BABYLON.serialize(),
  39963. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39964. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  39965. __decorate([
  39966. BABYLON.serialize(),
  39967. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39968. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  39969. __decorate([
  39970. BABYLON.serialize(),
  39971. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39972. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  39973. __decorate([
  39974. BABYLON.serialize(),
  39975. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39976. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  39977. __decorate([
  39978. BABYLON.serialize(),
  39979. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39980. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  39981. __decorate([
  39982. BABYLON.serialize(),
  39983. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39984. ], PBRMaterial.prototype, "useParallax", void 0);
  39985. __decorate([
  39986. BABYLON.serialize(),
  39987. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39988. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  39989. __decorate([
  39990. BABYLON.serialize(),
  39991. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39992. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  39993. __decorate([
  39994. BABYLON.serialize(),
  39995. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39996. ], PBRMaterial.prototype, "disableLighting", void 0);
  39997. __decorate([
  39998. BABYLON.serialize(),
  39999. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40000. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  40001. __decorate([
  40002. BABYLON.serialize(),
  40003. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40004. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  40005. __decorate([
  40006. BABYLON.serialize(),
  40007. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40008. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  40009. __decorate([
  40010. BABYLON.serialize(),
  40011. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40012. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  40013. __decorate([
  40014. BABYLON.serialize(),
  40015. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40016. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  40017. __decorate([
  40018. BABYLON.serialize(),
  40019. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40020. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  40021. __decorate([
  40022. BABYLON.serialize(),
  40023. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40024. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  40025. __decorate([
  40026. BABYLON.serializeAsTexture(),
  40027. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40028. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  40029. __decorate([
  40030. BABYLON.serialize(),
  40031. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40032. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  40033. __decorate([
  40034. BABYLON.serialize(),
  40035. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40036. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  40037. __decorate([
  40038. BABYLON.serialize(),
  40039. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40040. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  40041. return PBRMaterial;
  40042. }(BABYLON.PBRBaseMaterial));
  40043. BABYLON.PBRMaterial = PBRMaterial;
  40044. })(BABYLON || (BABYLON = {}));
  40045. //# sourceMappingURL=babylon.pbrMaterial.js.map
  40046. var BABYLON;
  40047. (function (BABYLON) {
  40048. /**
  40049. * The PBR material of BJS following the metal roughness convention.
  40050. *
  40051. * This fits to the PBR convention in the GLTF definition:
  40052. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  40053. */
  40054. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  40055. __extends(PBRMetallicRoughnessMaterial, _super);
  40056. /**
  40057. * Instantiates a new PBRMetalRoughnessMaterial instance.
  40058. *
  40059. * @param name The material name
  40060. * @param scene The scene the material will be use in.
  40061. */
  40062. function PBRMetallicRoughnessMaterial(name, scene) {
  40063. var _this = _super.call(this, name, scene) || this;
  40064. _this._useRoughnessFromMetallicTextureAlpha = false;
  40065. _this._useRoughnessFromMetallicTextureGreen = true;
  40066. _this._useMetallnessFromMetallicTextureBlue = true;
  40067. _this._forceMetallicWorkflow = true;
  40068. return _this;
  40069. }
  40070. /**
  40071. * Return the currrent class name of the material.
  40072. */
  40073. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  40074. return "PBRMetallicRoughnessMaterial";
  40075. };
  40076. /**
  40077. * Return the active textures of the material.
  40078. */
  40079. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  40080. var activeTextures = _super.prototype.getActiveTextures.call(this);
  40081. if (this.baseTexture) {
  40082. activeTextures.push(this.baseTexture);
  40083. }
  40084. if (this.metallicRoughnessTexture) {
  40085. activeTextures.push(this.metallicRoughnessTexture);
  40086. }
  40087. return activeTextures;
  40088. };
  40089. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  40090. if (_super.prototype.hasTexture.call(this, texture)) {
  40091. return true;
  40092. }
  40093. if (this.baseTexture === texture) {
  40094. return true;
  40095. }
  40096. if (this.metallicRoughnessTexture === texture) {
  40097. return true;
  40098. }
  40099. return false;
  40100. };
  40101. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  40102. var _this = this;
  40103. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  40104. clone.id = name;
  40105. clone.name = name;
  40106. return clone;
  40107. };
  40108. /**
  40109. * Serialize the material to a parsable JSON object.
  40110. */
  40111. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  40112. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  40113. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  40114. return serializationObject;
  40115. };
  40116. /**
  40117. * Parses a JSON object correponding to the serialize function.
  40118. */
  40119. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  40120. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  40121. };
  40122. __decorate([
  40123. BABYLON.serializeAsColor3(),
  40124. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  40125. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  40126. __decorate([
  40127. BABYLON.serializeAsTexture(),
  40128. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  40129. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  40130. __decorate([
  40131. BABYLON.serialize(),
  40132. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40133. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  40134. __decorate([
  40135. BABYLON.serialize(),
  40136. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40137. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  40138. __decorate([
  40139. BABYLON.serializeAsTexture(),
  40140. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  40141. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  40142. return PBRMetallicRoughnessMaterial;
  40143. }(BABYLON.PBRBaseSimpleMaterial));
  40144. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  40145. })(BABYLON || (BABYLON = {}));
  40146. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  40147. var BABYLON;
  40148. (function (BABYLON) {
  40149. /**
  40150. * The PBR material of BJS following the specular glossiness convention.
  40151. *
  40152. * This fits to the PBR convention in the GLTF definition:
  40153. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  40154. */
  40155. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  40156. __extends(PBRSpecularGlossinessMaterial, _super);
  40157. /**
  40158. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  40159. *
  40160. * @param name The material name
  40161. * @param scene The scene the material will be use in.
  40162. */
  40163. function PBRSpecularGlossinessMaterial(name, scene) {
  40164. var _this = _super.call(this, name, scene) || this;
  40165. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  40166. return _this;
  40167. }
  40168. /**
  40169. * Return the currrent class name of the material.
  40170. */
  40171. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  40172. return "PBRSpecularGlossinessMaterial";
  40173. };
  40174. /**
  40175. * Return the active textures of the material.
  40176. */
  40177. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  40178. var activeTextures = _super.prototype.getActiveTextures.call(this);
  40179. if (this.diffuseTexture) {
  40180. activeTextures.push(this.diffuseTexture);
  40181. }
  40182. if (this.specularGlossinessTexture) {
  40183. activeTextures.push(this.specularGlossinessTexture);
  40184. }
  40185. return activeTextures;
  40186. };
  40187. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  40188. if (_super.prototype.hasTexture.call(this, texture)) {
  40189. return true;
  40190. }
  40191. if (this.diffuseTexture === texture) {
  40192. return true;
  40193. }
  40194. if (this.specularGlossinessTexture === texture) {
  40195. return true;
  40196. }
  40197. return false;
  40198. };
  40199. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  40200. var _this = this;
  40201. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  40202. clone.id = name;
  40203. clone.name = name;
  40204. return clone;
  40205. };
  40206. /**
  40207. * Serialize the material to a parsable JSON object.
  40208. */
  40209. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  40210. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  40211. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  40212. return serializationObject;
  40213. };
  40214. /**
  40215. * Parses a JSON object correponding to the serialize function.
  40216. */
  40217. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  40218. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  40219. };
  40220. __decorate([
  40221. BABYLON.serializeAsColor3("diffuse"),
  40222. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  40223. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  40224. __decorate([
  40225. BABYLON.serializeAsTexture(),
  40226. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  40227. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  40228. __decorate([
  40229. BABYLON.serializeAsColor3("specular"),
  40230. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  40231. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  40232. __decorate([
  40233. BABYLON.serialize(),
  40234. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  40235. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  40236. __decorate([
  40237. BABYLON.serializeAsTexture(),
  40238. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  40239. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  40240. return PBRSpecularGlossinessMaterial;
  40241. }(BABYLON.PBRBaseSimpleMaterial));
  40242. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  40243. })(BABYLON || (BABYLON = {}));
  40244. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  40245. var BABYLON;
  40246. (function (BABYLON) {
  40247. BABYLON.CameraInputTypes = {};
  40248. var CameraInputsManager = /** @class */ (function () {
  40249. function CameraInputsManager(camera) {
  40250. this.attached = {};
  40251. this.camera = camera;
  40252. this.checkInputs = function () { };
  40253. }
  40254. /**
  40255. * Add an input method to a camera.
  40256. * builtin inputs example: camera.inputs.addGamepad();
  40257. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  40258. * @param input camera input method
  40259. */
  40260. CameraInputsManager.prototype.add = function (input) {
  40261. var type = input.getSimpleName();
  40262. if (this.attached[type]) {
  40263. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  40264. return;
  40265. }
  40266. this.attached[type] = input;
  40267. input.camera = this.camera;
  40268. //for checkInputs, we are dynamically creating a function
  40269. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  40270. if (input.checkInputs) {
  40271. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  40272. }
  40273. if (this.attachedElement) {
  40274. input.attachControl(this.attachedElement);
  40275. }
  40276. };
  40277. /**
  40278. * Remove a specific input method from a camera
  40279. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  40280. * @param inputToRemove camera input method
  40281. */
  40282. CameraInputsManager.prototype.remove = function (inputToRemove) {
  40283. for (var cam in this.attached) {
  40284. var input = this.attached[cam];
  40285. if (input === inputToRemove) {
  40286. input.detachControl(this.attachedElement);
  40287. input.camera = null;
  40288. delete this.attached[cam];
  40289. this.rebuildInputCheck();
  40290. }
  40291. }
  40292. };
  40293. CameraInputsManager.prototype.removeByType = function (inputType) {
  40294. for (var cam in this.attached) {
  40295. var input = this.attached[cam];
  40296. if (input.getClassName() === inputType) {
  40297. input.detachControl(this.attachedElement);
  40298. input.camera = null;
  40299. delete this.attached[cam];
  40300. this.rebuildInputCheck();
  40301. }
  40302. }
  40303. };
  40304. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  40305. var current = this.checkInputs;
  40306. return function () {
  40307. current();
  40308. fn();
  40309. };
  40310. };
  40311. CameraInputsManager.prototype.attachInput = function (input) {
  40312. if (this.attachedElement) {
  40313. input.attachControl(this.attachedElement, this.noPreventDefault);
  40314. }
  40315. };
  40316. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  40317. if (noPreventDefault === void 0) { noPreventDefault = false; }
  40318. if (this.attachedElement) {
  40319. return;
  40320. }
  40321. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  40322. this.attachedElement = element;
  40323. this.noPreventDefault = noPreventDefault;
  40324. for (var cam in this.attached) {
  40325. this.attached[cam].attachControl(element, noPreventDefault);
  40326. }
  40327. };
  40328. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  40329. if (disconnect === void 0) { disconnect = false; }
  40330. if (this.attachedElement !== element) {
  40331. return;
  40332. }
  40333. for (var cam in this.attached) {
  40334. this.attached[cam].detachControl(element);
  40335. if (disconnect) {
  40336. this.attached[cam].camera = null;
  40337. }
  40338. }
  40339. this.attachedElement = null;
  40340. };
  40341. CameraInputsManager.prototype.rebuildInputCheck = function () {
  40342. this.checkInputs = function () { };
  40343. for (var cam in this.attached) {
  40344. var input = this.attached[cam];
  40345. if (input.checkInputs) {
  40346. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  40347. }
  40348. }
  40349. };
  40350. /**
  40351. * Remove all attached input methods from a camera
  40352. */
  40353. CameraInputsManager.prototype.clear = function () {
  40354. if (this.attachedElement) {
  40355. this.detachElement(this.attachedElement, true);
  40356. }
  40357. this.attached = {};
  40358. this.attachedElement = null;
  40359. this.checkInputs = function () { };
  40360. };
  40361. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  40362. var inputs = {};
  40363. for (var cam in this.attached) {
  40364. var input = this.attached[cam];
  40365. var res = BABYLON.SerializationHelper.Serialize(input);
  40366. inputs[input.getClassName()] = res;
  40367. }
  40368. serializedCamera.inputsmgr = inputs;
  40369. };
  40370. CameraInputsManager.prototype.parse = function (parsedCamera) {
  40371. var parsedInputs = parsedCamera.inputsmgr;
  40372. if (parsedInputs) {
  40373. this.clear();
  40374. for (var n in parsedInputs) {
  40375. var construct = BABYLON.CameraInputTypes[n];
  40376. if (construct) {
  40377. var parsedinput = parsedInputs[n];
  40378. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  40379. this.add(input);
  40380. }
  40381. }
  40382. }
  40383. else {
  40384. //2016-03-08 this part is for managing backward compatibility
  40385. for (var n in this.attached) {
  40386. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  40387. if (construct) {
  40388. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  40389. this.remove(this.attached[n]);
  40390. this.add(input);
  40391. }
  40392. }
  40393. }
  40394. };
  40395. return CameraInputsManager;
  40396. }());
  40397. BABYLON.CameraInputsManager = CameraInputsManager;
  40398. })(BABYLON || (BABYLON = {}));
  40399. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  40400. var BABYLON;
  40401. (function (BABYLON) {
  40402. var TargetCamera = /** @class */ (function (_super) {
  40403. __extends(TargetCamera, _super);
  40404. function TargetCamera(name, position, scene) {
  40405. var _this = _super.call(this, name, position, scene) || this;
  40406. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  40407. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  40408. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  40409. _this.speed = 2.0;
  40410. _this.noRotationConstraint = false;
  40411. _this.lockedTarget = null;
  40412. _this._currentTarget = BABYLON.Vector3.Zero();
  40413. _this._viewMatrix = BABYLON.Matrix.Zero();
  40414. _this._camMatrix = BABYLON.Matrix.Zero();
  40415. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  40416. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  40417. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  40418. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  40419. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  40420. _this._lookAtTemp = BABYLON.Matrix.Zero();
  40421. _this._tempMatrix = BABYLON.Matrix.Zero();
  40422. return _this;
  40423. }
  40424. TargetCamera.prototype.getFrontPosition = function (distance) {
  40425. this.getWorldMatrix();
  40426. var direction = this.getTarget().subtract(this.position);
  40427. direction.normalize();
  40428. direction.scaleInPlace(distance);
  40429. return this.globalPosition.add(direction);
  40430. };
  40431. TargetCamera.prototype._getLockedTargetPosition = function () {
  40432. if (!this.lockedTarget) {
  40433. return null;
  40434. }
  40435. if (this.lockedTarget.absolutePosition) {
  40436. this.lockedTarget.computeWorldMatrix();
  40437. }
  40438. return this.lockedTarget.absolutePosition || this.lockedTarget;
  40439. };
  40440. TargetCamera.prototype.storeState = function () {
  40441. this._storedPosition = this.position.clone();
  40442. this._storedRotation = this.rotation.clone();
  40443. if (this.rotationQuaternion) {
  40444. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  40445. }
  40446. return _super.prototype.storeState.call(this);
  40447. };
  40448. /**
  40449. * Restored camera state. You must call storeState() first
  40450. */
  40451. TargetCamera.prototype._restoreStateValues = function () {
  40452. if (!_super.prototype._restoreStateValues.call(this)) {
  40453. return false;
  40454. }
  40455. this.position = this._storedPosition.clone();
  40456. this.rotation = this._storedRotation.clone();
  40457. if (this.rotationQuaternion) {
  40458. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  40459. }
  40460. this.cameraDirection.copyFromFloats(0, 0, 0);
  40461. this.cameraRotation.copyFromFloats(0, 0);
  40462. return true;
  40463. };
  40464. // Cache
  40465. TargetCamera.prototype._initCache = function () {
  40466. _super.prototype._initCache.call(this);
  40467. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  40468. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  40469. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  40470. };
  40471. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  40472. if (!ignoreParentClass) {
  40473. _super.prototype._updateCache.call(this);
  40474. }
  40475. var lockedTargetPosition = this._getLockedTargetPosition();
  40476. if (!lockedTargetPosition) {
  40477. this._cache.lockedTarget = null;
  40478. }
  40479. else {
  40480. if (!this._cache.lockedTarget) {
  40481. this._cache.lockedTarget = lockedTargetPosition.clone();
  40482. }
  40483. else {
  40484. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  40485. }
  40486. }
  40487. this._cache.rotation.copyFrom(this.rotation);
  40488. if (this.rotationQuaternion)
  40489. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  40490. };
  40491. // Synchronized
  40492. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  40493. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  40494. return false;
  40495. }
  40496. var lockedTargetPosition = this._getLockedTargetPosition();
  40497. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  40498. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  40499. };
  40500. // Methods
  40501. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  40502. var engine = this.getEngine();
  40503. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  40504. };
  40505. // Target
  40506. TargetCamera.prototype.setTarget = function (target) {
  40507. this.upVector.normalize();
  40508. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  40509. this._camMatrix.invert();
  40510. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  40511. var vDir = target.subtract(this.position);
  40512. if (vDir.x >= 0.0) {
  40513. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  40514. }
  40515. else {
  40516. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  40517. }
  40518. this.rotation.z = 0;
  40519. if (isNaN(this.rotation.x)) {
  40520. this.rotation.x = 0;
  40521. }
  40522. if (isNaN(this.rotation.y)) {
  40523. this.rotation.y = 0;
  40524. }
  40525. if (isNaN(this.rotation.z)) {
  40526. this.rotation.z = 0;
  40527. }
  40528. if (this.rotationQuaternion) {
  40529. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  40530. }
  40531. };
  40532. /**
  40533. * Return the current target position of the camera. This value is expressed in local space.
  40534. */
  40535. TargetCamera.prototype.getTarget = function () {
  40536. return this._currentTarget;
  40537. };
  40538. TargetCamera.prototype._decideIfNeedsToMove = function () {
  40539. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  40540. };
  40541. TargetCamera.prototype._updatePosition = function () {
  40542. if (this.parent) {
  40543. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  40544. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  40545. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  40546. return;
  40547. }
  40548. this.position.addInPlace(this.cameraDirection);
  40549. };
  40550. TargetCamera.prototype._checkInputs = function () {
  40551. var needToMove = this._decideIfNeedsToMove();
  40552. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  40553. // Move
  40554. if (needToMove) {
  40555. this._updatePosition();
  40556. }
  40557. // Rotate
  40558. if (needToRotate) {
  40559. this.rotation.x += this.cameraRotation.x;
  40560. this.rotation.y += this.cameraRotation.y;
  40561. //rotate, if quaternion is set and rotation was used
  40562. if (this.rotationQuaternion) {
  40563. var len = this.rotation.lengthSquared();
  40564. if (len) {
  40565. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  40566. }
  40567. }
  40568. if (!this.noRotationConstraint) {
  40569. var limit = (Math.PI / 2) * 0.95;
  40570. if (this.rotation.x > limit)
  40571. this.rotation.x = limit;
  40572. if (this.rotation.x < -limit)
  40573. this.rotation.x = -limit;
  40574. }
  40575. }
  40576. // Inertia
  40577. if (needToMove) {
  40578. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  40579. this.cameraDirection.x = 0;
  40580. }
  40581. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  40582. this.cameraDirection.y = 0;
  40583. }
  40584. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  40585. this.cameraDirection.z = 0;
  40586. }
  40587. this.cameraDirection.scaleInPlace(this.inertia);
  40588. }
  40589. if (needToRotate) {
  40590. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  40591. this.cameraRotation.x = 0;
  40592. }
  40593. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  40594. this.cameraRotation.y = 0;
  40595. }
  40596. this.cameraRotation.scaleInPlace(this.inertia);
  40597. }
  40598. _super.prototype._checkInputs.call(this);
  40599. };
  40600. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  40601. if (this.rotationQuaternion) {
  40602. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  40603. }
  40604. else {
  40605. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  40606. }
  40607. //update the up vector!
  40608. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  40609. };
  40610. TargetCamera.prototype._getViewMatrix = function () {
  40611. if (this.lockedTarget) {
  40612. this.setTarget(this._getLockedTargetPosition());
  40613. }
  40614. // Compute
  40615. this._updateCameraRotationMatrix();
  40616. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  40617. // Computing target and final matrix
  40618. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  40619. if (this.getScene().useRightHandedSystem) {
  40620. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  40621. }
  40622. else {
  40623. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  40624. }
  40625. return this._viewMatrix;
  40626. };
  40627. /**
  40628. * @override
  40629. * Override Camera.createRigCamera
  40630. */
  40631. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  40632. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  40633. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  40634. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  40635. if (!this.rotationQuaternion) {
  40636. this.rotationQuaternion = new BABYLON.Quaternion();
  40637. }
  40638. rigCamera._cameraRigParams = {};
  40639. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  40640. }
  40641. return rigCamera;
  40642. }
  40643. return null;
  40644. };
  40645. /**
  40646. * @override
  40647. * Override Camera._updateRigCameras
  40648. */
  40649. TargetCamera.prototype._updateRigCameras = function () {
  40650. var camLeft = this._rigCameras[0];
  40651. var camRight = this._rigCameras[1];
  40652. switch (this.cameraRigMode) {
  40653. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  40654. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  40655. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  40656. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  40657. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  40658. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  40659. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  40660. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  40661. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  40662. camLeft.setTarget(this.getTarget());
  40663. camRight.setTarget(this.getTarget());
  40664. break;
  40665. case BABYLON.Camera.RIG_MODE_VR:
  40666. if (camLeft.rotationQuaternion) {
  40667. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  40668. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  40669. }
  40670. else {
  40671. camLeft.rotation.copyFrom(this.rotation);
  40672. camRight.rotation.copyFrom(this.rotation);
  40673. }
  40674. camLeft.position.copyFrom(this.position);
  40675. camRight.position.copyFrom(this.position);
  40676. break;
  40677. }
  40678. _super.prototype._updateRigCameras.call(this);
  40679. };
  40680. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  40681. if (!this._rigCamTransformMatrix) {
  40682. this._rigCamTransformMatrix = new BABYLON.Matrix();
  40683. }
  40684. var target = this.getTarget();
  40685. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  40686. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  40687. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  40688. };
  40689. TargetCamera.prototype.getClassName = function () {
  40690. return "TargetCamera";
  40691. };
  40692. __decorate([
  40693. BABYLON.serializeAsVector3()
  40694. ], TargetCamera.prototype, "rotation", void 0);
  40695. __decorate([
  40696. BABYLON.serialize()
  40697. ], TargetCamera.prototype, "speed", void 0);
  40698. __decorate([
  40699. BABYLON.serializeAsMeshReference("lockedTargetId")
  40700. ], TargetCamera.prototype, "lockedTarget", void 0);
  40701. return TargetCamera;
  40702. }(BABYLON.Camera));
  40703. BABYLON.TargetCamera = TargetCamera;
  40704. })(BABYLON || (BABYLON = {}));
  40705. //# sourceMappingURL=babylon.targetCamera.js.map
  40706. var BABYLON;
  40707. (function (BABYLON) {
  40708. var FreeCameraMouseInput = /** @class */ (function () {
  40709. function FreeCameraMouseInput(touchEnabled) {
  40710. if (touchEnabled === void 0) { touchEnabled = true; }
  40711. this.touchEnabled = touchEnabled;
  40712. this.buttons = [0, 1, 2];
  40713. this.angularSensibility = 2000.0;
  40714. this.previousPosition = null;
  40715. }
  40716. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  40717. var _this = this;
  40718. var engine = this.camera.getEngine();
  40719. if (!this._pointerInput) {
  40720. this._pointerInput = function (p, s) {
  40721. var evt = p.event;
  40722. if (engine.isInVRExclusivePointerMode) {
  40723. return;
  40724. }
  40725. if (!_this.touchEnabled && evt.pointerType === "touch") {
  40726. return;
  40727. }
  40728. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  40729. return;
  40730. }
  40731. var srcElement = (evt.srcElement || evt.target);
  40732. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  40733. try {
  40734. srcElement.setPointerCapture(evt.pointerId);
  40735. }
  40736. catch (e) {
  40737. //Nothing to do with the error. Execution will continue.
  40738. }
  40739. _this.previousPosition = {
  40740. x: evt.clientX,
  40741. y: evt.clientY
  40742. };
  40743. if (!noPreventDefault) {
  40744. evt.preventDefault();
  40745. element.focus();
  40746. }
  40747. }
  40748. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  40749. try {
  40750. srcElement.releasePointerCapture(evt.pointerId);
  40751. }
  40752. catch (e) {
  40753. //Nothing to do with the error.
  40754. }
  40755. _this.previousPosition = null;
  40756. if (!noPreventDefault) {
  40757. evt.preventDefault();
  40758. }
  40759. }
  40760. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  40761. if (!_this.previousPosition || engine.isPointerLock) {
  40762. return;
  40763. }
  40764. var offsetX = evt.clientX - _this.previousPosition.x;
  40765. var offsetY = evt.clientY - _this.previousPosition.y;
  40766. if (_this.camera.getScene().useRightHandedSystem) {
  40767. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  40768. }
  40769. else {
  40770. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  40771. }
  40772. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  40773. _this.previousPosition = {
  40774. x: evt.clientX,
  40775. y: evt.clientY
  40776. };
  40777. if (!noPreventDefault) {
  40778. evt.preventDefault();
  40779. }
  40780. }
  40781. };
  40782. }
  40783. this._onMouseMove = function (evt) {
  40784. if (!engine.isPointerLock) {
  40785. return;
  40786. }
  40787. if (engine.isInVRExclusivePointerMode) {
  40788. return;
  40789. }
  40790. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  40791. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  40792. if (_this.camera.getScene().useRightHandedSystem) {
  40793. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  40794. }
  40795. else {
  40796. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  40797. }
  40798. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  40799. _this.previousPosition = null;
  40800. if (!noPreventDefault) {
  40801. evt.preventDefault();
  40802. }
  40803. };
  40804. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  40805. element.addEventListener("mousemove", this._onMouseMove, false);
  40806. };
  40807. FreeCameraMouseInput.prototype.detachControl = function (element) {
  40808. if (this._observer && element) {
  40809. this.camera.getScene().onPointerObservable.remove(this._observer);
  40810. if (this._onMouseMove) {
  40811. element.removeEventListener("mousemove", this._onMouseMove);
  40812. }
  40813. this._observer = null;
  40814. this._onMouseMove = null;
  40815. this.previousPosition = null;
  40816. }
  40817. };
  40818. FreeCameraMouseInput.prototype.getClassName = function () {
  40819. return "FreeCameraMouseInput";
  40820. };
  40821. FreeCameraMouseInput.prototype.getSimpleName = function () {
  40822. return "mouse";
  40823. };
  40824. __decorate([
  40825. BABYLON.serialize()
  40826. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  40827. __decorate([
  40828. BABYLON.serialize()
  40829. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  40830. return FreeCameraMouseInput;
  40831. }());
  40832. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  40833. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  40834. })(BABYLON || (BABYLON = {}));
  40835. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  40836. var BABYLON;
  40837. (function (BABYLON) {
  40838. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  40839. function FreeCameraKeyboardMoveInput() {
  40840. this._keys = new Array();
  40841. this.keysUp = [38];
  40842. this.keysDown = [40];
  40843. this.keysLeft = [37];
  40844. this.keysRight = [39];
  40845. }
  40846. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  40847. var _this = this;
  40848. if (this._onCanvasBlurObserver) {
  40849. return;
  40850. }
  40851. this._scene = this.camera.getScene();
  40852. this._engine = this._scene.getEngine();
  40853. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  40854. _this._keys = [];
  40855. });
  40856. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  40857. var evt = info.event;
  40858. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  40859. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  40860. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  40861. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  40862. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  40863. var index = _this._keys.indexOf(evt.keyCode);
  40864. if (index === -1) {
  40865. _this._keys.push(evt.keyCode);
  40866. }
  40867. if (!noPreventDefault) {
  40868. evt.preventDefault();
  40869. }
  40870. }
  40871. }
  40872. else {
  40873. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  40874. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  40875. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  40876. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  40877. var index = _this._keys.indexOf(evt.keyCode);
  40878. if (index >= 0) {
  40879. _this._keys.splice(index, 1);
  40880. }
  40881. if (!noPreventDefault) {
  40882. evt.preventDefault();
  40883. }
  40884. }
  40885. }
  40886. });
  40887. };
  40888. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  40889. if (this._scene) {
  40890. if (this._onKeyboardObserver) {
  40891. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  40892. }
  40893. if (this._onCanvasBlurObserver) {
  40894. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  40895. }
  40896. this._onKeyboardObserver = null;
  40897. this._onCanvasBlurObserver = null;
  40898. }
  40899. this._keys = [];
  40900. };
  40901. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  40902. if (this._onKeyboardObserver) {
  40903. var camera = this.camera;
  40904. // Keyboard
  40905. for (var index = 0; index < this._keys.length; index++) {
  40906. var keyCode = this._keys[index];
  40907. var speed = camera._computeLocalCameraSpeed();
  40908. if (this.keysLeft.indexOf(keyCode) !== -1) {
  40909. camera._localDirection.copyFromFloats(-speed, 0, 0);
  40910. }
  40911. else if (this.keysUp.indexOf(keyCode) !== -1) {
  40912. camera._localDirection.copyFromFloats(0, 0, speed);
  40913. }
  40914. else if (this.keysRight.indexOf(keyCode) !== -1) {
  40915. camera._localDirection.copyFromFloats(speed, 0, 0);
  40916. }
  40917. else if (this.keysDown.indexOf(keyCode) !== -1) {
  40918. camera._localDirection.copyFromFloats(0, 0, -speed);
  40919. }
  40920. if (camera.getScene().useRightHandedSystem) {
  40921. camera._localDirection.z *= -1;
  40922. }
  40923. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  40924. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  40925. camera.cameraDirection.addInPlace(camera._transformedDirection);
  40926. }
  40927. }
  40928. };
  40929. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  40930. return "FreeCameraKeyboardMoveInput";
  40931. };
  40932. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  40933. this._keys = [];
  40934. };
  40935. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  40936. return "keyboard";
  40937. };
  40938. __decorate([
  40939. BABYLON.serialize()
  40940. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  40941. __decorate([
  40942. BABYLON.serialize()
  40943. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  40944. __decorate([
  40945. BABYLON.serialize()
  40946. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  40947. __decorate([
  40948. BABYLON.serialize()
  40949. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  40950. return FreeCameraKeyboardMoveInput;
  40951. }());
  40952. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  40953. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  40954. })(BABYLON || (BABYLON = {}));
  40955. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  40956. var BABYLON;
  40957. (function (BABYLON) {
  40958. var FreeCameraInputsManager = /** @class */ (function (_super) {
  40959. __extends(FreeCameraInputsManager, _super);
  40960. function FreeCameraInputsManager(camera) {
  40961. return _super.call(this, camera) || this;
  40962. }
  40963. FreeCameraInputsManager.prototype.addKeyboard = function () {
  40964. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  40965. return this;
  40966. };
  40967. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  40968. if (touchEnabled === void 0) { touchEnabled = true; }
  40969. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  40970. return this;
  40971. };
  40972. FreeCameraInputsManager.prototype.addGamepad = function () {
  40973. this.add(new BABYLON.FreeCameraGamepadInput());
  40974. return this;
  40975. };
  40976. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  40977. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  40978. return this;
  40979. };
  40980. FreeCameraInputsManager.prototype.addTouch = function () {
  40981. this.add(new BABYLON.FreeCameraTouchInput());
  40982. return this;
  40983. };
  40984. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  40985. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  40986. return this;
  40987. };
  40988. return FreeCameraInputsManager;
  40989. }(BABYLON.CameraInputsManager));
  40990. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  40991. })(BABYLON || (BABYLON = {}));
  40992. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  40993. var BABYLON;
  40994. (function (BABYLON) {
  40995. var FreeCamera = /** @class */ (function (_super) {
  40996. __extends(FreeCamera, _super);
  40997. function FreeCamera(name, position, scene) {
  40998. var _this = _super.call(this, name, position, scene) || this;
  40999. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  41000. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  41001. _this.checkCollisions = false;
  41002. _this.applyGravity = false;
  41003. _this._needMoveForGravity = false;
  41004. _this._oldPosition = BABYLON.Vector3.Zero();
  41005. _this._diffPosition = BABYLON.Vector3.Zero();
  41006. _this._newPosition = BABYLON.Vector3.Zero();
  41007. // Collisions
  41008. _this._collisionMask = -1;
  41009. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  41010. if (collidedMesh === void 0) { collidedMesh = null; }
  41011. //TODO move this to the collision coordinator!
  41012. if (_this.getScene().workerCollisions)
  41013. newPosition.multiplyInPlace(_this._collider._radius);
  41014. var updatePosition = function (newPos) {
  41015. _this._newPosition.copyFrom(newPos);
  41016. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  41017. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  41018. _this.position.addInPlace(_this._diffPosition);
  41019. if (_this.onCollide && collidedMesh) {
  41020. _this.onCollide(collidedMesh);
  41021. }
  41022. }
  41023. };
  41024. updatePosition(newPosition);
  41025. };
  41026. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  41027. _this.inputs.addKeyboard().addMouse();
  41028. return _this;
  41029. }
  41030. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  41031. //-- begin properties for backward compatibility for inputs
  41032. /**
  41033. * Gets the input sensibility for a mouse input. (default is 2000.0)
  41034. * Higher values reduce sensitivity.
  41035. */
  41036. get: function () {
  41037. var mouse = this.inputs.attached["mouse"];
  41038. if (mouse)
  41039. return mouse.angularSensibility;
  41040. return 0;
  41041. },
  41042. /**
  41043. * Sets the input sensibility for a mouse input. (default is 2000.0)
  41044. * Higher values reduce sensitivity.
  41045. */
  41046. set: function (value) {
  41047. var mouse = this.inputs.attached["mouse"];
  41048. if (mouse)
  41049. mouse.angularSensibility = value;
  41050. },
  41051. enumerable: true,
  41052. configurable: true
  41053. });
  41054. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  41055. get: function () {
  41056. var keyboard = this.inputs.attached["keyboard"];
  41057. if (keyboard)
  41058. return keyboard.keysUp;
  41059. return [];
  41060. },
  41061. set: function (value) {
  41062. var keyboard = this.inputs.attached["keyboard"];
  41063. if (keyboard)
  41064. keyboard.keysUp = value;
  41065. },
  41066. enumerable: true,
  41067. configurable: true
  41068. });
  41069. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  41070. get: function () {
  41071. var keyboard = this.inputs.attached["keyboard"];
  41072. if (keyboard)
  41073. return keyboard.keysDown;
  41074. return [];
  41075. },
  41076. set: function (value) {
  41077. var keyboard = this.inputs.attached["keyboard"];
  41078. if (keyboard)
  41079. keyboard.keysDown = value;
  41080. },
  41081. enumerable: true,
  41082. configurable: true
  41083. });
  41084. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  41085. get: function () {
  41086. var keyboard = this.inputs.attached["keyboard"];
  41087. if (keyboard)
  41088. return keyboard.keysLeft;
  41089. return [];
  41090. },
  41091. set: function (value) {
  41092. var keyboard = this.inputs.attached["keyboard"];
  41093. if (keyboard)
  41094. keyboard.keysLeft = value;
  41095. },
  41096. enumerable: true,
  41097. configurable: true
  41098. });
  41099. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  41100. get: function () {
  41101. var keyboard = this.inputs.attached["keyboard"];
  41102. if (keyboard)
  41103. return keyboard.keysRight;
  41104. return [];
  41105. },
  41106. set: function (value) {
  41107. var keyboard = this.inputs.attached["keyboard"];
  41108. if (keyboard)
  41109. keyboard.keysRight = value;
  41110. },
  41111. enumerable: true,
  41112. configurable: true
  41113. });
  41114. // Controls
  41115. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  41116. this.inputs.attachElement(element, noPreventDefault);
  41117. };
  41118. FreeCamera.prototype.detachControl = function (element) {
  41119. this.inputs.detachElement(element);
  41120. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  41121. this.cameraRotation = new BABYLON.Vector2(0, 0);
  41122. };
  41123. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  41124. get: function () {
  41125. return this._collisionMask;
  41126. },
  41127. set: function (mask) {
  41128. this._collisionMask = !isNaN(mask) ? mask : -1;
  41129. },
  41130. enumerable: true,
  41131. configurable: true
  41132. });
  41133. FreeCamera.prototype._collideWithWorld = function (displacement) {
  41134. var globalPosition;
  41135. if (this.parent) {
  41136. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  41137. }
  41138. else {
  41139. globalPosition = this.position;
  41140. }
  41141. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  41142. this._oldPosition.addInPlace(this.ellipsoidOffset);
  41143. if (!this._collider) {
  41144. this._collider = new BABYLON.Collider();
  41145. }
  41146. this._collider._radius = this.ellipsoid;
  41147. this._collider.collisionMask = this._collisionMask;
  41148. //no need for clone, as long as gravity is not on.
  41149. var actualDisplacement = displacement;
  41150. //add gravity to the direction to prevent the dual-collision checking
  41151. if (this.applyGravity) {
  41152. //this prevents mending with cameraDirection, a global variable of the free camera class.
  41153. actualDisplacement = displacement.add(this.getScene().gravity);
  41154. }
  41155. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  41156. };
  41157. FreeCamera.prototype._checkInputs = function () {
  41158. if (!this._localDirection) {
  41159. this._localDirection = BABYLON.Vector3.Zero();
  41160. this._transformedDirection = BABYLON.Vector3.Zero();
  41161. }
  41162. this.inputs.checkInputs();
  41163. _super.prototype._checkInputs.call(this);
  41164. };
  41165. FreeCamera.prototype._decideIfNeedsToMove = function () {
  41166. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  41167. };
  41168. FreeCamera.prototype._updatePosition = function () {
  41169. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  41170. this._collideWithWorld(this.cameraDirection);
  41171. }
  41172. else {
  41173. _super.prototype._updatePosition.call(this);
  41174. }
  41175. };
  41176. FreeCamera.prototype.dispose = function () {
  41177. this.inputs.clear();
  41178. _super.prototype.dispose.call(this);
  41179. };
  41180. FreeCamera.prototype.getClassName = function () {
  41181. return "FreeCamera";
  41182. };
  41183. __decorate([
  41184. BABYLON.serializeAsVector3()
  41185. ], FreeCamera.prototype, "ellipsoid", void 0);
  41186. __decorate([
  41187. BABYLON.serializeAsVector3()
  41188. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  41189. __decorate([
  41190. BABYLON.serialize()
  41191. ], FreeCamera.prototype, "checkCollisions", void 0);
  41192. __decorate([
  41193. BABYLON.serialize()
  41194. ], FreeCamera.prototype, "applyGravity", void 0);
  41195. return FreeCamera;
  41196. }(BABYLON.TargetCamera));
  41197. BABYLON.FreeCamera = FreeCamera;
  41198. })(BABYLON || (BABYLON = {}));
  41199. //# sourceMappingURL=babylon.freeCamera.js.map
  41200. var BABYLON;
  41201. (function (BABYLON) {
  41202. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  41203. function ArcRotateCameraKeyboardMoveInput() {
  41204. this._keys = new Array();
  41205. this.keysUp = [38];
  41206. this.keysDown = [40];
  41207. this.keysLeft = [37];
  41208. this.keysRight = [39];
  41209. this.keysReset = [220];
  41210. this.panningSensibility = 50.0;
  41211. this.zoomingSensibility = 25.0;
  41212. this.useAltToZoom = true;
  41213. }
  41214. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  41215. var _this = this;
  41216. if (this._onCanvasBlurObserver) {
  41217. return;
  41218. }
  41219. this._scene = this.camera.getScene();
  41220. this._engine = this._scene.getEngine();
  41221. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  41222. _this._keys = [];
  41223. });
  41224. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  41225. var evt = info.event;
  41226. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  41227. _this._ctrlPressed = evt.ctrlKey;
  41228. _this._altPressed = evt.altKey;
  41229. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  41230. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  41231. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  41232. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  41233. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  41234. var index = _this._keys.indexOf(evt.keyCode);
  41235. if (index === -1) {
  41236. _this._keys.push(evt.keyCode);
  41237. }
  41238. if (evt.preventDefault) {
  41239. if (!noPreventDefault) {
  41240. evt.preventDefault();
  41241. }
  41242. }
  41243. }
  41244. }
  41245. else {
  41246. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  41247. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  41248. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  41249. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  41250. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  41251. var index = _this._keys.indexOf(evt.keyCode);
  41252. if (index >= 0) {
  41253. _this._keys.splice(index, 1);
  41254. }
  41255. if (evt.preventDefault) {
  41256. if (!noPreventDefault) {
  41257. evt.preventDefault();
  41258. }
  41259. }
  41260. }
  41261. }
  41262. });
  41263. };
  41264. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  41265. if (this._scene) {
  41266. if (this._onKeyboardObserver) {
  41267. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  41268. }
  41269. if (this._onCanvasBlurObserver) {
  41270. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  41271. }
  41272. this._onKeyboardObserver = null;
  41273. this._onCanvasBlurObserver = null;
  41274. }
  41275. this._keys = [];
  41276. };
  41277. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  41278. if (this._onKeyboardObserver) {
  41279. var camera = this.camera;
  41280. for (var index = 0; index < this._keys.length; index++) {
  41281. var keyCode = this._keys[index];
  41282. if (this.keysLeft.indexOf(keyCode) !== -1) {
  41283. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  41284. camera.inertialPanningX -= 1 / this.panningSensibility;
  41285. }
  41286. else {
  41287. camera.inertialAlphaOffset -= 0.01;
  41288. }
  41289. }
  41290. else if (this.keysUp.indexOf(keyCode) !== -1) {
  41291. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  41292. camera.inertialPanningY += 1 / this.panningSensibility;
  41293. }
  41294. else if (this._altPressed && this.useAltToZoom) {
  41295. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  41296. }
  41297. else {
  41298. camera.inertialBetaOffset -= 0.01;
  41299. }
  41300. }
  41301. else if (this.keysRight.indexOf(keyCode) !== -1) {
  41302. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  41303. camera.inertialPanningX += 1 / this.panningSensibility;
  41304. }
  41305. else {
  41306. camera.inertialAlphaOffset += 0.01;
  41307. }
  41308. }
  41309. else if (this.keysDown.indexOf(keyCode) !== -1) {
  41310. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  41311. camera.inertialPanningY -= 1 / this.panningSensibility;
  41312. }
  41313. else if (this._altPressed && this.useAltToZoom) {
  41314. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  41315. }
  41316. else {
  41317. camera.inertialBetaOffset += 0.01;
  41318. }
  41319. }
  41320. else if (this.keysReset.indexOf(keyCode) !== -1) {
  41321. camera.restoreState();
  41322. }
  41323. }
  41324. }
  41325. };
  41326. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  41327. return "ArcRotateCameraKeyboardMoveInput";
  41328. };
  41329. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  41330. return "keyboard";
  41331. };
  41332. __decorate([
  41333. BABYLON.serialize()
  41334. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  41335. __decorate([
  41336. BABYLON.serialize()
  41337. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  41338. __decorate([
  41339. BABYLON.serialize()
  41340. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  41341. __decorate([
  41342. BABYLON.serialize()
  41343. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  41344. __decorate([
  41345. BABYLON.serialize()
  41346. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  41347. __decorate([
  41348. BABYLON.serialize()
  41349. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  41350. __decorate([
  41351. BABYLON.serialize()
  41352. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  41353. __decorate([
  41354. BABYLON.serialize()
  41355. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  41356. return ArcRotateCameraKeyboardMoveInput;
  41357. }());
  41358. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  41359. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  41360. })(BABYLON || (BABYLON = {}));
  41361. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  41362. var BABYLON;
  41363. (function (BABYLON) {
  41364. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  41365. function ArcRotateCameraMouseWheelInput() {
  41366. this.wheelPrecision = 3.0;
  41367. /**
  41368. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  41369. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  41370. */
  41371. this.wheelDeltaPercentage = 0;
  41372. }
  41373. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  41374. var _this = this;
  41375. this._wheel = function (p, s) {
  41376. //sanity check - this should be a PointerWheel event.
  41377. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  41378. return;
  41379. var event = p.event;
  41380. var delta = 0;
  41381. if (event.wheelDelta) {
  41382. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  41383. }
  41384. else if (event.detail) {
  41385. delta = -event.detail / _this.wheelPrecision;
  41386. }
  41387. if (delta)
  41388. _this.camera.inertialRadiusOffset += delta;
  41389. if (event.preventDefault) {
  41390. if (!noPreventDefault) {
  41391. event.preventDefault();
  41392. }
  41393. }
  41394. };
  41395. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  41396. };
  41397. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  41398. if (this._observer && element) {
  41399. this.camera.getScene().onPointerObservable.remove(this._observer);
  41400. this._observer = null;
  41401. this._wheel = null;
  41402. }
  41403. };
  41404. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  41405. return "ArcRotateCameraMouseWheelInput";
  41406. };
  41407. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  41408. return "mousewheel";
  41409. };
  41410. __decorate([
  41411. BABYLON.serialize()
  41412. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  41413. __decorate([
  41414. BABYLON.serialize()
  41415. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  41416. return ArcRotateCameraMouseWheelInput;
  41417. }());
  41418. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  41419. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  41420. })(BABYLON || (BABYLON = {}));
  41421. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  41422. var BABYLON;
  41423. (function (BABYLON) {
  41424. var ArcRotateCameraPointersInput = /** @class */ (function () {
  41425. function ArcRotateCameraPointersInput() {
  41426. this.buttons = [0, 1, 2];
  41427. this.angularSensibilityX = 1000.0;
  41428. this.angularSensibilityY = 1000.0;
  41429. this.pinchPrecision = 12.0;
  41430. /**
  41431. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  41432. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  41433. */
  41434. this.pinchDeltaPercentage = 0;
  41435. this.panningSensibility = 1000.0;
  41436. this.multiTouchPanning = true;
  41437. this.multiTouchPanAndZoom = true;
  41438. this._isPanClick = false;
  41439. this.pinchInwards = true;
  41440. }
  41441. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  41442. var _this = this;
  41443. var engine = this.camera.getEngine();
  41444. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  41445. var pointA = null;
  41446. var pointB = null;
  41447. var previousPinchSquaredDistance = 0;
  41448. var initialDistance = 0;
  41449. var twoFingerActivityCount = 0;
  41450. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  41451. this._pointerInput = function (p, s) {
  41452. var evt = p.event;
  41453. var isTouch = p.event.pointerType === "touch";
  41454. if (engine.isInVRExclusivePointerMode) {
  41455. return;
  41456. }
  41457. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  41458. return;
  41459. }
  41460. var srcElement = (evt.srcElement || evt.target);
  41461. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  41462. try {
  41463. srcElement.setPointerCapture(evt.pointerId);
  41464. }
  41465. catch (e) {
  41466. //Nothing to do with the error. Execution will continue.
  41467. }
  41468. // Manage panning with pan button click
  41469. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  41470. // manage pointers
  41471. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  41472. if (pointA === null) {
  41473. pointA = cacheSoloPointer;
  41474. }
  41475. else if (pointB === null) {
  41476. pointB = cacheSoloPointer;
  41477. }
  41478. if (!noPreventDefault) {
  41479. evt.preventDefault();
  41480. element.focus();
  41481. }
  41482. }
  41483. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  41484. _this.camera.restoreState();
  41485. }
  41486. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  41487. try {
  41488. srcElement.releasePointerCapture(evt.pointerId);
  41489. }
  41490. catch (e) {
  41491. //Nothing to do with the error.
  41492. }
  41493. cacheSoloPointer = null;
  41494. previousPinchSquaredDistance = 0;
  41495. previousMultiTouchPanPosition.isPaning = false;
  41496. previousMultiTouchPanPosition.isPinching = false;
  41497. twoFingerActivityCount = 0;
  41498. initialDistance = 0;
  41499. if (!isTouch) {
  41500. pointB = null; // Mouse and pen are mono pointer
  41501. }
  41502. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  41503. //but emptying completly pointers collection is required to fix a bug on iPhone :
  41504. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  41505. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  41506. if (engine.badOS) {
  41507. pointA = pointB = null;
  41508. }
  41509. else {
  41510. //only remove the impacted pointer in case of multitouch allowing on most
  41511. //platforms switching from rotate to zoom and pan seamlessly.
  41512. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  41513. pointA = pointB;
  41514. pointB = null;
  41515. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  41516. }
  41517. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  41518. pointB = null;
  41519. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  41520. }
  41521. else {
  41522. pointA = pointB = null;
  41523. }
  41524. }
  41525. if (!noPreventDefault) {
  41526. evt.preventDefault();
  41527. }
  41528. }
  41529. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  41530. if (!noPreventDefault) {
  41531. evt.preventDefault();
  41532. }
  41533. // One button down
  41534. if (pointA && pointB === null && cacheSoloPointer) {
  41535. if (_this.panningSensibility !== 0 &&
  41536. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  41537. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  41538. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  41539. }
  41540. else {
  41541. var offsetX = evt.clientX - cacheSoloPointer.x;
  41542. var offsetY = evt.clientY - cacheSoloPointer.y;
  41543. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  41544. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  41545. }
  41546. cacheSoloPointer.x = evt.clientX;
  41547. cacheSoloPointer.y = evt.clientY;
  41548. }
  41549. else if (pointA && pointB) {
  41550. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  41551. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  41552. ed.x = evt.clientX;
  41553. ed.y = evt.clientY;
  41554. var direction = _this.pinchInwards ? 1 : -1;
  41555. var distX = pointA.x - pointB.x;
  41556. var distY = pointA.y - pointB.y;
  41557. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  41558. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  41559. if (previousPinchSquaredDistance === 0) {
  41560. initialDistance = pinchDistance;
  41561. previousPinchSquaredDistance = pinchSquaredDistance;
  41562. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  41563. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  41564. return;
  41565. }
  41566. if (_this.multiTouchPanAndZoom) {
  41567. if (_this.pinchDeltaPercentage) {
  41568. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  41569. }
  41570. else {
  41571. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  41572. (_this.pinchPrecision *
  41573. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  41574. direction);
  41575. }
  41576. if (_this.panningSensibility !== 0) {
  41577. var pointersCenterX = (pointA.x + pointB.x) / 2;
  41578. var pointersCenterY = (pointA.y + pointB.y) / 2;
  41579. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  41580. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  41581. previousMultiTouchPanPosition.x = pointersCenterX;
  41582. previousMultiTouchPanPosition.y = pointersCenterY;
  41583. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  41584. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  41585. }
  41586. }
  41587. else {
  41588. twoFingerActivityCount++;
  41589. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  41590. if (_this.pinchDeltaPercentage) {
  41591. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  41592. }
  41593. else {
  41594. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  41595. (_this.pinchPrecision *
  41596. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  41597. direction);
  41598. }
  41599. previousMultiTouchPanPosition.isPaning = false;
  41600. previousMultiTouchPanPosition.isPinching = true;
  41601. }
  41602. else {
  41603. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  41604. if (!previousMultiTouchPanPosition.isPaning) {
  41605. previousMultiTouchPanPosition.isPaning = true;
  41606. previousMultiTouchPanPosition.isPinching = false;
  41607. previousMultiTouchPanPosition.x = ed.x;
  41608. previousMultiTouchPanPosition.y = ed.y;
  41609. return;
  41610. }
  41611. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  41612. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  41613. }
  41614. }
  41615. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  41616. previousMultiTouchPanPosition.x = ed.x;
  41617. previousMultiTouchPanPosition.y = ed.y;
  41618. }
  41619. }
  41620. previousPinchSquaredDistance = pinchSquaredDistance;
  41621. }
  41622. }
  41623. };
  41624. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  41625. this._onContextMenu = function (evt) {
  41626. evt.preventDefault();
  41627. };
  41628. if (!this.camera._useCtrlForPanning) {
  41629. element.addEventListener("contextmenu", this._onContextMenu, false);
  41630. }
  41631. this._onLostFocus = function () {
  41632. //this._keys = [];
  41633. pointA = pointB = null;
  41634. previousPinchSquaredDistance = 0;
  41635. previousMultiTouchPanPosition.isPaning = false;
  41636. previousMultiTouchPanPosition.isPinching = false;
  41637. twoFingerActivityCount = 0;
  41638. cacheSoloPointer = null;
  41639. initialDistance = 0;
  41640. };
  41641. this._onMouseMove = function (evt) {
  41642. if (!engine.isPointerLock) {
  41643. return;
  41644. }
  41645. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  41646. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  41647. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  41648. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  41649. if (!noPreventDefault) {
  41650. evt.preventDefault();
  41651. }
  41652. };
  41653. this._onGestureStart = function (e) {
  41654. if (window.MSGesture === undefined) {
  41655. return;
  41656. }
  41657. if (!_this._MSGestureHandler) {
  41658. _this._MSGestureHandler = new MSGesture();
  41659. _this._MSGestureHandler.target = element;
  41660. }
  41661. _this._MSGestureHandler.addPointer(e.pointerId);
  41662. };
  41663. this._onGesture = function (e) {
  41664. _this.camera.radius *= e.scale;
  41665. if (e.preventDefault) {
  41666. if (!noPreventDefault) {
  41667. e.stopPropagation();
  41668. e.preventDefault();
  41669. }
  41670. }
  41671. };
  41672. element.addEventListener("mousemove", this._onMouseMove, false);
  41673. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  41674. element.addEventListener("MSGestureChange", this._onGesture, false);
  41675. BABYLON.Tools.RegisterTopRootEvents([
  41676. { name: "blur", handler: this._onLostFocus }
  41677. ]);
  41678. };
  41679. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  41680. if (this._onLostFocus) {
  41681. BABYLON.Tools.UnregisterTopRootEvents([
  41682. { name: "blur", handler: this._onLostFocus }
  41683. ]);
  41684. }
  41685. if (element && this._observer) {
  41686. this.camera.getScene().onPointerObservable.remove(this._observer);
  41687. this._observer = null;
  41688. if (this._onContextMenu) {
  41689. element.removeEventListener("contextmenu", this._onContextMenu);
  41690. }
  41691. if (this._onMouseMove) {
  41692. element.removeEventListener("mousemove", this._onMouseMove);
  41693. }
  41694. if (this._onGestureStart) {
  41695. element.removeEventListener("MSPointerDown", this._onGestureStart);
  41696. }
  41697. if (this._onGesture) {
  41698. element.removeEventListener("MSGestureChange", this._onGesture);
  41699. }
  41700. this._isPanClick = false;
  41701. this.pinchInwards = true;
  41702. this._onMouseMove = null;
  41703. this._onGestureStart = null;
  41704. this._onGesture = null;
  41705. this._MSGestureHandler = null;
  41706. this._onLostFocus = null;
  41707. this._onContextMenu = null;
  41708. }
  41709. };
  41710. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  41711. return "ArcRotateCameraPointersInput";
  41712. };
  41713. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  41714. return "pointers";
  41715. };
  41716. __decorate([
  41717. BABYLON.serialize()
  41718. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  41719. __decorate([
  41720. BABYLON.serialize()
  41721. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  41722. __decorate([
  41723. BABYLON.serialize()
  41724. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  41725. __decorate([
  41726. BABYLON.serialize()
  41727. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  41728. __decorate([
  41729. BABYLON.serialize()
  41730. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  41731. __decorate([
  41732. BABYLON.serialize()
  41733. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  41734. __decorate([
  41735. BABYLON.serialize()
  41736. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  41737. __decorate([
  41738. BABYLON.serialize()
  41739. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  41740. return ArcRotateCameraPointersInput;
  41741. }());
  41742. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  41743. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  41744. })(BABYLON || (BABYLON = {}));
  41745. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  41746. var BABYLON;
  41747. (function (BABYLON) {
  41748. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  41749. __extends(ArcRotateCameraInputsManager, _super);
  41750. function ArcRotateCameraInputsManager(camera) {
  41751. return _super.call(this, camera) || this;
  41752. }
  41753. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  41754. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  41755. return this;
  41756. };
  41757. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  41758. this.add(new BABYLON.ArcRotateCameraPointersInput());
  41759. return this;
  41760. };
  41761. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  41762. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  41763. return this;
  41764. };
  41765. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  41766. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  41767. return this;
  41768. };
  41769. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  41770. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  41771. return this;
  41772. };
  41773. return ArcRotateCameraInputsManager;
  41774. }(BABYLON.CameraInputsManager));
  41775. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  41776. })(BABYLON || (BABYLON = {}));
  41777. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  41778. var BABYLON;
  41779. (function (BABYLON) {
  41780. var ArcRotateCamera = /** @class */ (function (_super) {
  41781. __extends(ArcRotateCamera, _super);
  41782. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  41783. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  41784. _this.inertialAlphaOffset = 0;
  41785. _this.inertialBetaOffset = 0;
  41786. _this.inertialRadiusOffset = 0;
  41787. _this.lowerAlphaLimit = null;
  41788. _this.upperAlphaLimit = null;
  41789. _this.lowerBetaLimit = 0.01;
  41790. _this.upperBetaLimit = Math.PI;
  41791. _this.lowerRadiusLimit = null;
  41792. _this.upperRadiusLimit = null;
  41793. _this.inertialPanningX = 0;
  41794. _this.inertialPanningY = 0;
  41795. _this.pinchToPanMaxDistance = 20;
  41796. _this.panningDistanceLimit = null;
  41797. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  41798. _this.panningInertia = 0.9;
  41799. //-- end properties for backward compatibility for inputs
  41800. _this.zoomOnFactor = 1;
  41801. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  41802. _this.allowUpsideDown = true;
  41803. _this._viewMatrix = new BABYLON.Matrix();
  41804. // Panning
  41805. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  41806. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  41807. _this.checkCollisions = false;
  41808. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  41809. _this._previousPosition = BABYLON.Vector3.Zero();
  41810. _this._collisionVelocity = BABYLON.Vector3.Zero();
  41811. _this._newPosition = BABYLON.Vector3.Zero();
  41812. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  41813. if (collidedMesh === void 0) { collidedMesh = null; }
  41814. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  41815. newPosition.multiplyInPlace(_this._collider._radius);
  41816. }
  41817. if (!collidedMesh) {
  41818. _this._previousPosition.copyFrom(_this.position);
  41819. }
  41820. else {
  41821. _this.setPosition(newPosition);
  41822. if (_this.onCollide) {
  41823. _this.onCollide(collidedMesh);
  41824. }
  41825. }
  41826. // Recompute because of constraints
  41827. var cosa = Math.cos(_this.alpha);
  41828. var sina = Math.sin(_this.alpha);
  41829. var cosb = Math.cos(_this.beta);
  41830. var sinb = Math.sin(_this.beta);
  41831. if (sinb === 0) {
  41832. sinb = 0.0001;
  41833. }
  41834. var target = _this._getTargetPosition();
  41835. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  41836. _this.position.copyFrom(_this._newPosition);
  41837. var up = _this.upVector;
  41838. if (_this.allowUpsideDown && _this.beta < 0) {
  41839. up = up.clone();
  41840. up = up.negate();
  41841. }
  41842. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  41843. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  41844. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  41845. _this._collisionTriggered = false;
  41846. };
  41847. _this._target = BABYLON.Vector3.Zero();
  41848. if (target) {
  41849. _this.setTarget(target);
  41850. }
  41851. _this.alpha = alpha;
  41852. _this.beta = beta;
  41853. _this.radius = radius;
  41854. _this.getViewMatrix();
  41855. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  41856. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  41857. return _this;
  41858. }
  41859. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  41860. get: function () {
  41861. return this._target;
  41862. },
  41863. set: function (value) {
  41864. this.setTarget(value);
  41865. },
  41866. enumerable: true,
  41867. configurable: true
  41868. });
  41869. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  41870. //-- begin properties for backward compatibility for inputs
  41871. get: function () {
  41872. var pointers = this.inputs.attached["pointers"];
  41873. if (pointers)
  41874. return pointers.angularSensibilityX;
  41875. return 0;
  41876. },
  41877. set: function (value) {
  41878. var pointers = this.inputs.attached["pointers"];
  41879. if (pointers) {
  41880. pointers.angularSensibilityX = value;
  41881. }
  41882. },
  41883. enumerable: true,
  41884. configurable: true
  41885. });
  41886. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  41887. get: function () {
  41888. var pointers = this.inputs.attached["pointers"];
  41889. if (pointers)
  41890. return pointers.angularSensibilityY;
  41891. return 0;
  41892. },
  41893. set: function (value) {
  41894. var pointers = this.inputs.attached["pointers"];
  41895. if (pointers) {
  41896. pointers.angularSensibilityY = value;
  41897. }
  41898. },
  41899. enumerable: true,
  41900. configurable: true
  41901. });
  41902. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  41903. get: function () {
  41904. var pointers = this.inputs.attached["pointers"];
  41905. if (pointers)
  41906. return pointers.pinchPrecision;
  41907. return 0;
  41908. },
  41909. set: function (value) {
  41910. var pointers = this.inputs.attached["pointers"];
  41911. if (pointers) {
  41912. pointers.pinchPrecision = value;
  41913. }
  41914. },
  41915. enumerable: true,
  41916. configurable: true
  41917. });
  41918. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  41919. get: function () {
  41920. var pointers = this.inputs.attached["pointers"];
  41921. if (pointers)
  41922. return pointers.pinchDeltaPercentage;
  41923. return 0;
  41924. },
  41925. set: function (value) {
  41926. var pointers = this.inputs.attached["pointers"];
  41927. if (pointers) {
  41928. pointers.pinchDeltaPercentage = value;
  41929. }
  41930. },
  41931. enumerable: true,
  41932. configurable: true
  41933. });
  41934. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  41935. get: function () {
  41936. var pointers = this.inputs.attached["pointers"];
  41937. if (pointers)
  41938. return pointers.panningSensibility;
  41939. return 0;
  41940. },
  41941. set: function (value) {
  41942. var pointers = this.inputs.attached["pointers"];
  41943. if (pointers) {
  41944. pointers.panningSensibility = value;
  41945. }
  41946. },
  41947. enumerable: true,
  41948. configurable: true
  41949. });
  41950. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  41951. get: function () {
  41952. var keyboard = this.inputs.attached["keyboard"];
  41953. if (keyboard)
  41954. return keyboard.keysUp;
  41955. return [];
  41956. },
  41957. set: function (value) {
  41958. var keyboard = this.inputs.attached["keyboard"];
  41959. if (keyboard)
  41960. keyboard.keysUp = value;
  41961. },
  41962. enumerable: true,
  41963. configurable: true
  41964. });
  41965. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  41966. get: function () {
  41967. var keyboard = this.inputs.attached["keyboard"];
  41968. if (keyboard)
  41969. return keyboard.keysDown;
  41970. return [];
  41971. },
  41972. set: function (value) {
  41973. var keyboard = this.inputs.attached["keyboard"];
  41974. if (keyboard)
  41975. keyboard.keysDown = value;
  41976. },
  41977. enumerable: true,
  41978. configurable: true
  41979. });
  41980. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  41981. get: function () {
  41982. var keyboard = this.inputs.attached["keyboard"];
  41983. if (keyboard)
  41984. return keyboard.keysLeft;
  41985. return [];
  41986. },
  41987. set: function (value) {
  41988. var keyboard = this.inputs.attached["keyboard"];
  41989. if (keyboard)
  41990. keyboard.keysLeft = value;
  41991. },
  41992. enumerable: true,
  41993. configurable: true
  41994. });
  41995. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  41996. get: function () {
  41997. var keyboard = this.inputs.attached["keyboard"];
  41998. if (keyboard)
  41999. return keyboard.keysRight;
  42000. return [];
  42001. },
  42002. set: function (value) {
  42003. var keyboard = this.inputs.attached["keyboard"];
  42004. if (keyboard)
  42005. keyboard.keysRight = value;
  42006. },
  42007. enumerable: true,
  42008. configurable: true
  42009. });
  42010. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  42011. get: function () {
  42012. var mousewheel = this.inputs.attached["mousewheel"];
  42013. if (mousewheel)
  42014. return mousewheel.wheelPrecision;
  42015. return 0;
  42016. },
  42017. set: function (value) {
  42018. var mousewheel = this.inputs.attached["mousewheel"];
  42019. if (mousewheel)
  42020. mousewheel.wheelPrecision = value;
  42021. },
  42022. enumerable: true,
  42023. configurable: true
  42024. });
  42025. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  42026. get: function () {
  42027. var mousewheel = this.inputs.attached["mousewheel"];
  42028. if (mousewheel)
  42029. return mousewheel.wheelDeltaPercentage;
  42030. return 0;
  42031. },
  42032. set: function (value) {
  42033. var mousewheel = this.inputs.attached["mousewheel"];
  42034. if (mousewheel)
  42035. mousewheel.wheelDeltaPercentage = value;
  42036. },
  42037. enumerable: true,
  42038. configurable: true
  42039. });
  42040. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  42041. get: function () {
  42042. return this._bouncingBehavior;
  42043. },
  42044. enumerable: true,
  42045. configurable: true
  42046. });
  42047. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  42048. get: function () {
  42049. return this._bouncingBehavior != null;
  42050. },
  42051. set: function (value) {
  42052. if (value === this.useBouncingBehavior) {
  42053. return;
  42054. }
  42055. if (value) {
  42056. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  42057. this.addBehavior(this._bouncingBehavior);
  42058. }
  42059. else if (this._bouncingBehavior) {
  42060. this.removeBehavior(this._bouncingBehavior);
  42061. this._bouncingBehavior = null;
  42062. }
  42063. },
  42064. enumerable: true,
  42065. configurable: true
  42066. });
  42067. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  42068. get: function () {
  42069. return this._framingBehavior;
  42070. },
  42071. enumerable: true,
  42072. configurable: true
  42073. });
  42074. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  42075. get: function () {
  42076. return this._framingBehavior != null;
  42077. },
  42078. set: function (value) {
  42079. if (value === this.useFramingBehavior) {
  42080. return;
  42081. }
  42082. if (value) {
  42083. this._framingBehavior = new BABYLON.FramingBehavior();
  42084. this.addBehavior(this._framingBehavior);
  42085. }
  42086. else if (this._framingBehavior) {
  42087. this.removeBehavior(this._framingBehavior);
  42088. this._framingBehavior = null;
  42089. }
  42090. },
  42091. enumerable: true,
  42092. configurable: true
  42093. });
  42094. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  42095. get: function () {
  42096. return this._autoRotationBehavior;
  42097. },
  42098. enumerable: true,
  42099. configurable: true
  42100. });
  42101. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  42102. get: function () {
  42103. return this._autoRotationBehavior != null;
  42104. },
  42105. set: function (value) {
  42106. if (value === this.useAutoRotationBehavior) {
  42107. return;
  42108. }
  42109. if (value) {
  42110. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  42111. this.addBehavior(this._autoRotationBehavior);
  42112. }
  42113. else if (this._autoRotationBehavior) {
  42114. this.removeBehavior(this._autoRotationBehavior);
  42115. this._autoRotationBehavior = null;
  42116. }
  42117. },
  42118. enumerable: true,
  42119. configurable: true
  42120. });
  42121. // Cache
  42122. ArcRotateCamera.prototype._initCache = function () {
  42123. _super.prototype._initCache.call(this);
  42124. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42125. this._cache.alpha = undefined;
  42126. this._cache.beta = undefined;
  42127. this._cache.radius = undefined;
  42128. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  42129. };
  42130. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  42131. if (!ignoreParentClass) {
  42132. _super.prototype._updateCache.call(this);
  42133. }
  42134. this._cache._target.copyFrom(this._getTargetPosition());
  42135. this._cache.alpha = this.alpha;
  42136. this._cache.beta = this.beta;
  42137. this._cache.radius = this.radius;
  42138. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  42139. };
  42140. ArcRotateCamera.prototype._getTargetPosition = function () {
  42141. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  42142. var pos = this._targetHost.getAbsolutePosition();
  42143. if (this._targetBoundingCenter) {
  42144. pos.addToRef(this._targetBoundingCenter, this._target);
  42145. }
  42146. else {
  42147. this._target.copyFrom(pos);
  42148. }
  42149. }
  42150. var lockedTargetPosition = this._getLockedTargetPosition();
  42151. if (lockedTargetPosition) {
  42152. return lockedTargetPosition;
  42153. }
  42154. return this._target;
  42155. };
  42156. ArcRotateCamera.prototype.storeState = function () {
  42157. this._storedAlpha = this.alpha;
  42158. this._storedBeta = this.beta;
  42159. this._storedRadius = this.radius;
  42160. this._storedTarget = this._getTargetPosition().clone();
  42161. return _super.prototype.storeState.call(this);
  42162. };
  42163. /**
  42164. * Restored camera state. You must call storeState() first
  42165. */
  42166. ArcRotateCamera.prototype._restoreStateValues = function () {
  42167. if (!_super.prototype._restoreStateValues.call(this)) {
  42168. return false;
  42169. }
  42170. this.alpha = this._storedAlpha;
  42171. this.beta = this._storedBeta;
  42172. this.radius = this._storedRadius;
  42173. this.setTarget(this._storedTarget.clone());
  42174. this.inertialAlphaOffset = 0;
  42175. this.inertialBetaOffset = 0;
  42176. this.inertialRadiusOffset = 0;
  42177. this.inertialPanningX = 0;
  42178. this.inertialPanningY = 0;
  42179. return true;
  42180. };
  42181. // Synchronized
  42182. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  42183. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  42184. return false;
  42185. return this._cache._target.equals(this._getTargetPosition())
  42186. && this._cache.alpha === this.alpha
  42187. && this._cache.beta === this.beta
  42188. && this._cache.radius === this.radius
  42189. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  42190. };
  42191. // Methods
  42192. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  42193. var _this = this;
  42194. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  42195. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  42196. this._useCtrlForPanning = useCtrlForPanning;
  42197. this._panningMouseButton = panningMouseButton;
  42198. this.inputs.attachElement(element, noPreventDefault);
  42199. this._reset = function () {
  42200. _this.inertialAlphaOffset = 0;
  42201. _this.inertialBetaOffset = 0;
  42202. _this.inertialRadiusOffset = 0;
  42203. _this.inertialPanningX = 0;
  42204. _this.inertialPanningY = 0;
  42205. };
  42206. };
  42207. ArcRotateCamera.prototype.detachControl = function (element) {
  42208. this.inputs.detachElement(element);
  42209. if (this._reset) {
  42210. this._reset();
  42211. }
  42212. };
  42213. ArcRotateCamera.prototype._checkInputs = function () {
  42214. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  42215. if (this._collisionTriggered) {
  42216. return;
  42217. }
  42218. this.inputs.checkInputs();
  42219. // Inertia
  42220. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  42221. if (this.getScene().useRightHandedSystem) {
  42222. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  42223. }
  42224. else {
  42225. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  42226. }
  42227. this.beta += this.inertialBetaOffset;
  42228. this.radius -= this.inertialRadiusOffset;
  42229. this.inertialAlphaOffset *= this.inertia;
  42230. this.inertialBetaOffset *= this.inertia;
  42231. this.inertialRadiusOffset *= this.inertia;
  42232. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  42233. this.inertialAlphaOffset = 0;
  42234. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  42235. this.inertialBetaOffset = 0;
  42236. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  42237. this.inertialRadiusOffset = 0;
  42238. }
  42239. // Panning inertia
  42240. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  42241. if (!this._localDirection) {
  42242. this._localDirection = BABYLON.Vector3.Zero();
  42243. this._transformedDirection = BABYLON.Vector3.Zero();
  42244. }
  42245. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  42246. this._localDirection.multiplyInPlace(this.panningAxis);
  42247. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  42248. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  42249. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  42250. if (!this.panningAxis.y) {
  42251. this._transformedDirection.y = 0;
  42252. }
  42253. if (!this._targetHost) {
  42254. if (this.panningDistanceLimit) {
  42255. this._transformedDirection.addInPlace(this._target);
  42256. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  42257. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  42258. this._target.copyFrom(this._transformedDirection);
  42259. }
  42260. }
  42261. else {
  42262. this._target.addInPlace(this._transformedDirection);
  42263. }
  42264. }
  42265. this.inertialPanningX *= this.panningInertia;
  42266. this.inertialPanningY *= this.panningInertia;
  42267. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  42268. this.inertialPanningX = 0;
  42269. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  42270. this.inertialPanningY = 0;
  42271. }
  42272. // Limits
  42273. this._checkLimits();
  42274. _super.prototype._checkInputs.call(this);
  42275. };
  42276. ArcRotateCamera.prototype._checkLimits = function () {
  42277. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  42278. if (this.allowUpsideDown && this.beta > Math.PI) {
  42279. this.beta = this.beta - (2 * Math.PI);
  42280. }
  42281. }
  42282. else {
  42283. if (this.beta < this.lowerBetaLimit) {
  42284. this.beta = this.lowerBetaLimit;
  42285. }
  42286. }
  42287. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  42288. if (this.allowUpsideDown && this.beta < -Math.PI) {
  42289. this.beta = this.beta + (2 * Math.PI);
  42290. }
  42291. }
  42292. else {
  42293. if (this.beta > this.upperBetaLimit) {
  42294. this.beta = this.upperBetaLimit;
  42295. }
  42296. }
  42297. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  42298. this.alpha = this.lowerAlphaLimit;
  42299. }
  42300. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  42301. this.alpha = this.upperAlphaLimit;
  42302. }
  42303. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  42304. this.radius = this.lowerRadiusLimit;
  42305. }
  42306. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  42307. this.radius = this.upperRadiusLimit;
  42308. }
  42309. };
  42310. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  42311. var radiusv3 = this.position.subtract(this._getTargetPosition());
  42312. this.radius = radiusv3.length();
  42313. if (this.radius === 0) {
  42314. this.radius = 0.0001; // Just to avoid division by zero
  42315. }
  42316. // Alpha
  42317. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  42318. if (radiusv3.z < 0) {
  42319. this.alpha = 2 * Math.PI - this.alpha;
  42320. }
  42321. // Beta
  42322. this.beta = Math.acos(radiusv3.y / this.radius);
  42323. this._checkLimits();
  42324. };
  42325. ArcRotateCamera.prototype.setPosition = function (position) {
  42326. if (this.position.equals(position)) {
  42327. return;
  42328. }
  42329. this.position.copyFrom(position);
  42330. this.rebuildAnglesAndRadius();
  42331. };
  42332. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  42333. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  42334. if (allowSamePosition === void 0) { allowSamePosition = false; }
  42335. if (target.getBoundingInfo) {
  42336. if (toBoundingCenter) {
  42337. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  42338. }
  42339. else {
  42340. this._targetBoundingCenter = null;
  42341. }
  42342. this._targetHost = target;
  42343. this._target = this._getTargetPosition();
  42344. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  42345. }
  42346. else {
  42347. var newTarget = target;
  42348. var currentTarget = this._getTargetPosition();
  42349. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  42350. return;
  42351. }
  42352. this._targetHost = null;
  42353. this._target = newTarget;
  42354. this._targetBoundingCenter = null;
  42355. this.onMeshTargetChangedObservable.notifyObservers(null);
  42356. }
  42357. this.rebuildAnglesAndRadius();
  42358. };
  42359. ArcRotateCamera.prototype._getViewMatrix = function () {
  42360. // Compute
  42361. var cosa = Math.cos(this.alpha);
  42362. var sina = Math.sin(this.alpha);
  42363. var cosb = Math.cos(this.beta);
  42364. var sinb = Math.sin(this.beta);
  42365. if (sinb === 0) {
  42366. sinb = 0.0001;
  42367. }
  42368. var target = this._getTargetPosition();
  42369. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  42370. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  42371. if (!this._collider) {
  42372. this._collider = new BABYLON.Collider();
  42373. }
  42374. this._collider._radius = this.collisionRadius;
  42375. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  42376. this._collisionTriggered = true;
  42377. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  42378. }
  42379. else {
  42380. this.position.copyFrom(this._newPosition);
  42381. var up = this.upVector;
  42382. if (this.allowUpsideDown && sinb < 0) {
  42383. up = up.clone();
  42384. up = up.negate();
  42385. }
  42386. if (this.getScene().useRightHandedSystem) {
  42387. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  42388. }
  42389. else {
  42390. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  42391. }
  42392. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  42393. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  42394. }
  42395. this._currentTarget = target;
  42396. return this._viewMatrix;
  42397. };
  42398. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  42399. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  42400. meshes = meshes || this.getScene().meshes;
  42401. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  42402. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  42403. this.radius = distance * this.zoomOnFactor;
  42404. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  42405. };
  42406. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  42407. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  42408. var meshesOrMinMaxVector;
  42409. var distance;
  42410. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  42411. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  42412. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  42413. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  42414. }
  42415. else {
  42416. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  42417. meshesOrMinMaxVector = minMaxVectorAndDistance;
  42418. distance = minMaxVectorAndDistance.distance;
  42419. }
  42420. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  42421. if (!doNotUpdateMaxZ) {
  42422. this.maxZ = distance * 2;
  42423. }
  42424. };
  42425. /**
  42426. * @override
  42427. * Override Camera.createRigCamera
  42428. */
  42429. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  42430. var alphaShift = 0;
  42431. switch (this.cameraRigMode) {
  42432. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  42433. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  42434. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  42435. case BABYLON.Camera.RIG_MODE_VR:
  42436. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  42437. break;
  42438. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  42439. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  42440. break;
  42441. }
  42442. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  42443. rigCam._cameraRigParams = {};
  42444. return rigCam;
  42445. };
  42446. /**
  42447. * @override
  42448. * Override Camera._updateRigCameras
  42449. */
  42450. ArcRotateCamera.prototype._updateRigCameras = function () {
  42451. var camLeft = this._rigCameras[0];
  42452. var camRight = this._rigCameras[1];
  42453. camLeft.beta = camRight.beta = this.beta;
  42454. camLeft.radius = camRight.radius = this.radius;
  42455. switch (this.cameraRigMode) {
  42456. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  42457. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  42458. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  42459. case BABYLON.Camera.RIG_MODE_VR:
  42460. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  42461. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  42462. break;
  42463. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  42464. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  42465. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  42466. break;
  42467. }
  42468. _super.prototype._updateRigCameras.call(this);
  42469. };
  42470. ArcRotateCamera.prototype.dispose = function () {
  42471. this.inputs.clear();
  42472. _super.prototype.dispose.call(this);
  42473. };
  42474. ArcRotateCamera.prototype.getClassName = function () {
  42475. return "ArcRotateCamera";
  42476. };
  42477. __decorate([
  42478. BABYLON.serialize()
  42479. ], ArcRotateCamera.prototype, "alpha", void 0);
  42480. __decorate([
  42481. BABYLON.serialize()
  42482. ], ArcRotateCamera.prototype, "beta", void 0);
  42483. __decorate([
  42484. BABYLON.serialize()
  42485. ], ArcRotateCamera.prototype, "radius", void 0);
  42486. __decorate([
  42487. BABYLON.serializeAsVector3("target")
  42488. ], ArcRotateCamera.prototype, "_target", void 0);
  42489. __decorate([
  42490. BABYLON.serialize()
  42491. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  42492. __decorate([
  42493. BABYLON.serialize()
  42494. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  42495. __decorate([
  42496. BABYLON.serialize()
  42497. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  42498. __decorate([
  42499. BABYLON.serialize()
  42500. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  42501. __decorate([
  42502. BABYLON.serialize()
  42503. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  42504. __decorate([
  42505. BABYLON.serialize()
  42506. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  42507. __decorate([
  42508. BABYLON.serialize()
  42509. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  42510. __decorate([
  42511. BABYLON.serialize()
  42512. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  42513. __decorate([
  42514. BABYLON.serialize()
  42515. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  42516. __decorate([
  42517. BABYLON.serialize()
  42518. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  42519. __decorate([
  42520. BABYLON.serialize()
  42521. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  42522. __decorate([
  42523. BABYLON.serialize()
  42524. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  42525. __decorate([
  42526. BABYLON.serialize()
  42527. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  42528. __decorate([
  42529. BABYLON.serializeAsVector3()
  42530. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  42531. __decorate([
  42532. BABYLON.serialize()
  42533. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  42534. __decorate([
  42535. BABYLON.serialize()
  42536. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  42537. __decorate([
  42538. BABYLON.serialize()
  42539. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  42540. return ArcRotateCamera;
  42541. }(BABYLON.TargetCamera));
  42542. BABYLON.ArcRotateCamera = ArcRotateCamera;
  42543. })(BABYLON || (BABYLON = {}));
  42544. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  42545. var BABYLON;
  42546. (function (BABYLON) {
  42547. var HemisphericLight = /** @class */ (function (_super) {
  42548. __extends(HemisphericLight, _super);
  42549. /**
  42550. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  42551. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  42552. * The HemisphericLight can't cast shadows.
  42553. * Documentation : http://doc.babylonjs.com/tutorials/lights
  42554. */
  42555. function HemisphericLight(name, direction, scene) {
  42556. var _this = _super.call(this, name, scene) || this;
  42557. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  42558. _this.direction = direction || BABYLON.Vector3.Up();
  42559. return _this;
  42560. }
  42561. HemisphericLight.prototype._buildUniformLayout = function () {
  42562. this._uniformBuffer.addUniform("vLightData", 4);
  42563. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  42564. this._uniformBuffer.addUniform("vLightSpecular", 3);
  42565. this._uniformBuffer.addUniform("vLightGround", 3);
  42566. this._uniformBuffer.addUniform("shadowsInfo", 3);
  42567. this._uniformBuffer.addUniform("depthValues", 2);
  42568. this._uniformBuffer.create();
  42569. };
  42570. /**
  42571. * Returns the string "HemisphericLight".
  42572. */
  42573. HemisphericLight.prototype.getClassName = function () {
  42574. return "HemisphericLight";
  42575. };
  42576. /**
  42577. * Sets the HemisphericLight direction towards the passed target (Vector3).
  42578. * Returns the updated direction.
  42579. */
  42580. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  42581. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  42582. return this.direction;
  42583. };
  42584. HemisphericLight.prototype.getShadowGenerator = function () {
  42585. return null;
  42586. };
  42587. /**
  42588. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  42589. * Returns the HemisphericLight.
  42590. */
  42591. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  42592. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  42593. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  42594. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  42595. return this;
  42596. };
  42597. HemisphericLight.prototype._getWorldMatrix = function () {
  42598. if (!this._worldMatrix) {
  42599. this._worldMatrix = BABYLON.Matrix.Identity();
  42600. }
  42601. return this._worldMatrix;
  42602. };
  42603. /**
  42604. * Returns the integer 3.
  42605. */
  42606. HemisphericLight.prototype.getTypeID = function () {
  42607. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  42608. };
  42609. __decorate([
  42610. BABYLON.serializeAsColor3()
  42611. ], HemisphericLight.prototype, "groundColor", void 0);
  42612. __decorate([
  42613. BABYLON.serializeAsVector3()
  42614. ], HemisphericLight.prototype, "direction", void 0);
  42615. return HemisphericLight;
  42616. }(BABYLON.Light));
  42617. BABYLON.HemisphericLight = HemisphericLight;
  42618. })(BABYLON || (BABYLON = {}));
  42619. //# sourceMappingURL=babylon.hemisphericLight.js.map
  42620. var BABYLON;
  42621. (function (BABYLON) {
  42622. var ShadowLight = /** @class */ (function (_super) {
  42623. __extends(ShadowLight, _super);
  42624. function ShadowLight() {
  42625. var _this = _super !== null && _super.apply(this, arguments) || this;
  42626. _this._needProjectionMatrixCompute = true;
  42627. return _this;
  42628. }
  42629. Object.defineProperty(ShadowLight.prototype, "direction", {
  42630. get: function () {
  42631. return this._direction;
  42632. },
  42633. set: function (value) {
  42634. this._direction = value;
  42635. },
  42636. enumerable: true,
  42637. configurable: true
  42638. });
  42639. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  42640. get: function () {
  42641. return this._shadowMinZ;
  42642. },
  42643. set: function (value) {
  42644. this._shadowMinZ = value;
  42645. this.forceProjectionMatrixCompute();
  42646. },
  42647. enumerable: true,
  42648. configurable: true
  42649. });
  42650. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  42651. get: function () {
  42652. return this._shadowMaxZ;
  42653. },
  42654. set: function (value) {
  42655. this._shadowMaxZ = value;
  42656. this.forceProjectionMatrixCompute();
  42657. },
  42658. enumerable: true,
  42659. configurable: true
  42660. });
  42661. /**
  42662. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  42663. */
  42664. ShadowLight.prototype.computeTransformedInformation = function () {
  42665. if (this.parent && this.parent.getWorldMatrix) {
  42666. if (!this.transformedPosition) {
  42667. this.transformedPosition = BABYLON.Vector3.Zero();
  42668. }
  42669. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  42670. // In case the direction is present.
  42671. if (this.direction) {
  42672. if (!this.transformedDirection) {
  42673. this.transformedDirection = BABYLON.Vector3.Zero();
  42674. }
  42675. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  42676. }
  42677. return true;
  42678. }
  42679. return false;
  42680. };
  42681. /**
  42682. * Return the depth scale used for the shadow map.
  42683. */
  42684. ShadowLight.prototype.getDepthScale = function () {
  42685. return 50.0;
  42686. };
  42687. /**
  42688. * Returns the light direction (Vector3) for any passed face index.
  42689. */
  42690. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  42691. return this.transformedDirection ? this.transformedDirection : this.direction;
  42692. };
  42693. /**
  42694. * Returns the ShadowLight absolute position in the World.
  42695. */
  42696. ShadowLight.prototype.getAbsolutePosition = function () {
  42697. return this.transformedPosition ? this.transformedPosition : this.position;
  42698. };
  42699. /**
  42700. * Sets the ShadowLight direction toward the passed target (Vector3).
  42701. * Returns the updated ShadowLight direction (Vector3).
  42702. */
  42703. ShadowLight.prototype.setDirectionToTarget = function (target) {
  42704. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  42705. return this.direction;
  42706. };
  42707. /**
  42708. * Returns the light rotation (Vector3).
  42709. */
  42710. ShadowLight.prototype.getRotation = function () {
  42711. this.direction.normalize();
  42712. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  42713. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  42714. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  42715. };
  42716. /**
  42717. * Boolean : false by default.
  42718. */
  42719. ShadowLight.prototype.needCube = function () {
  42720. return false;
  42721. };
  42722. /**
  42723. * Specifies wether or not the projection matrix should be recomputed this frame.
  42724. */
  42725. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  42726. return this._needProjectionMatrixCompute;
  42727. };
  42728. /**
  42729. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  42730. */
  42731. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  42732. this._needProjectionMatrixCompute = true;
  42733. };
  42734. /**
  42735. * Get the world matrix of the sahdow lights.
  42736. */
  42737. ShadowLight.prototype._getWorldMatrix = function () {
  42738. if (!this._worldMatrix) {
  42739. this._worldMatrix = BABYLON.Matrix.Identity();
  42740. }
  42741. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  42742. return this._worldMatrix;
  42743. };
  42744. /**
  42745. * Gets the minZ used for shadow according to both the scene and the light.
  42746. * @param activeCamera
  42747. */
  42748. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  42749. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  42750. };
  42751. /**
  42752. * Gets the maxZ used for shadow according to both the scene and the light.
  42753. * @param activeCamera
  42754. */
  42755. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  42756. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  42757. };
  42758. /**
  42759. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  42760. * Returns the light.
  42761. */
  42762. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  42763. if (this.customProjectionMatrixBuilder) {
  42764. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  42765. }
  42766. else {
  42767. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  42768. }
  42769. return this;
  42770. };
  42771. __decorate([
  42772. BABYLON.serializeAsVector3()
  42773. ], ShadowLight.prototype, "position", void 0);
  42774. __decorate([
  42775. BABYLON.serializeAsVector3()
  42776. ], ShadowLight.prototype, "direction", null);
  42777. __decorate([
  42778. BABYLON.serialize()
  42779. ], ShadowLight.prototype, "shadowMinZ", null);
  42780. __decorate([
  42781. BABYLON.serialize()
  42782. ], ShadowLight.prototype, "shadowMaxZ", null);
  42783. return ShadowLight;
  42784. }(BABYLON.Light));
  42785. BABYLON.ShadowLight = ShadowLight;
  42786. })(BABYLON || (BABYLON = {}));
  42787. //# sourceMappingURL=babylon.shadowLight.js.map
  42788. var BABYLON;
  42789. (function (BABYLON) {
  42790. var PointLight = /** @class */ (function (_super) {
  42791. __extends(PointLight, _super);
  42792. /**
  42793. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  42794. * A PointLight emits the light in every direction.
  42795. * It can cast shadows.
  42796. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  42797. * ```javascript
  42798. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  42799. * ```
  42800. * Documentation : http://doc.babylonjs.com/tutorials/lights
  42801. */
  42802. function PointLight(name, position, scene) {
  42803. var _this = _super.call(this, name, scene) || this;
  42804. _this._shadowAngle = Math.PI / 2;
  42805. _this.position = position;
  42806. return _this;
  42807. }
  42808. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  42809. /**
  42810. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  42811. * This specifies what angle the shadow will use to be created.
  42812. *
  42813. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  42814. */
  42815. get: function () {
  42816. return this._shadowAngle;
  42817. },
  42818. /**
  42819. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  42820. * This specifies what angle the shadow will use to be created.
  42821. *
  42822. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  42823. */
  42824. set: function (value) {
  42825. this._shadowAngle = value;
  42826. this.forceProjectionMatrixCompute();
  42827. },
  42828. enumerable: true,
  42829. configurable: true
  42830. });
  42831. Object.defineProperty(PointLight.prototype, "direction", {
  42832. get: function () {
  42833. return this._direction;
  42834. },
  42835. /**
  42836. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  42837. */
  42838. set: function (value) {
  42839. var previousNeedCube = this.needCube();
  42840. this._direction = value;
  42841. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  42842. this._shadowGenerator.recreateShadowMap();
  42843. }
  42844. },
  42845. enumerable: true,
  42846. configurable: true
  42847. });
  42848. /**
  42849. * Returns the string "PointLight"
  42850. */
  42851. PointLight.prototype.getClassName = function () {
  42852. return "PointLight";
  42853. };
  42854. /**
  42855. * Returns the integer 0.
  42856. */
  42857. PointLight.prototype.getTypeID = function () {
  42858. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  42859. };
  42860. /**
  42861. * Specifies wether or not the shadowmap should be a cube texture.
  42862. */
  42863. PointLight.prototype.needCube = function () {
  42864. return !this.direction;
  42865. };
  42866. /**
  42867. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  42868. */
  42869. PointLight.prototype.getShadowDirection = function (faceIndex) {
  42870. if (this.direction) {
  42871. return _super.prototype.getShadowDirection.call(this, faceIndex);
  42872. }
  42873. else {
  42874. switch (faceIndex) {
  42875. case 0:
  42876. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  42877. case 1:
  42878. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  42879. case 2:
  42880. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  42881. case 3:
  42882. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  42883. case 4:
  42884. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  42885. case 5:
  42886. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  42887. }
  42888. }
  42889. return BABYLON.Vector3.Zero();
  42890. };
  42891. /**
  42892. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  42893. * - fov = PI / 2
  42894. * - aspect ratio : 1.0
  42895. * - z-near and far equal to the active camera minZ and maxZ.
  42896. * Returns the PointLight.
  42897. */
  42898. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  42899. var activeCamera = this.getScene().activeCamera;
  42900. if (!activeCamera) {
  42901. return;
  42902. }
  42903. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  42904. };
  42905. PointLight.prototype._buildUniformLayout = function () {
  42906. this._uniformBuffer.addUniform("vLightData", 4);
  42907. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  42908. this._uniformBuffer.addUniform("vLightSpecular", 3);
  42909. this._uniformBuffer.addUniform("shadowsInfo", 3);
  42910. this._uniformBuffer.addUniform("depthValues", 2);
  42911. this._uniformBuffer.create();
  42912. };
  42913. /**
  42914. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  42915. * Returns the PointLight.
  42916. */
  42917. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  42918. if (this.computeTransformedInformation()) {
  42919. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  42920. return this;
  42921. }
  42922. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  42923. return this;
  42924. };
  42925. __decorate([
  42926. BABYLON.serialize()
  42927. ], PointLight.prototype, "shadowAngle", null);
  42928. return PointLight;
  42929. }(BABYLON.ShadowLight));
  42930. BABYLON.PointLight = PointLight;
  42931. })(BABYLON || (BABYLON = {}));
  42932. //# sourceMappingURL=babylon.pointLight.js.map
  42933. var BABYLON;
  42934. (function (BABYLON) {
  42935. var DirectionalLight = /** @class */ (function (_super) {
  42936. __extends(DirectionalLight, _super);
  42937. /**
  42938. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  42939. * The directional light is emitted from everywhere in the given direction.
  42940. * It can cast shawdows.
  42941. * Documentation : http://doc.babylonjs.com/tutorials/lights
  42942. */
  42943. function DirectionalLight(name, direction, scene) {
  42944. var _this = _super.call(this, name, scene) || this;
  42945. _this._shadowFrustumSize = 0;
  42946. _this._shadowOrthoScale = 0.5;
  42947. _this.autoUpdateExtends = true;
  42948. // Cache
  42949. _this._orthoLeft = Number.MAX_VALUE;
  42950. _this._orthoRight = Number.MIN_VALUE;
  42951. _this._orthoTop = Number.MIN_VALUE;
  42952. _this._orthoBottom = Number.MAX_VALUE;
  42953. _this.position = direction.scale(-1.0);
  42954. _this.direction = direction;
  42955. return _this;
  42956. }
  42957. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  42958. /**
  42959. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  42960. */
  42961. get: function () {
  42962. return this._shadowFrustumSize;
  42963. },
  42964. /**
  42965. * Specifies a fix frustum size for the shadow generation.
  42966. */
  42967. set: function (value) {
  42968. this._shadowFrustumSize = value;
  42969. this.forceProjectionMatrixCompute();
  42970. },
  42971. enumerable: true,
  42972. configurable: true
  42973. });
  42974. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  42975. get: function () {
  42976. return this._shadowOrthoScale;
  42977. },
  42978. set: function (value) {
  42979. this._shadowOrthoScale = value;
  42980. this.forceProjectionMatrixCompute();
  42981. },
  42982. enumerable: true,
  42983. configurable: true
  42984. });
  42985. /**
  42986. * Returns the string "DirectionalLight".
  42987. */
  42988. DirectionalLight.prototype.getClassName = function () {
  42989. return "DirectionalLight";
  42990. };
  42991. /**
  42992. * Returns the integer 1.
  42993. */
  42994. DirectionalLight.prototype.getTypeID = function () {
  42995. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  42996. };
  42997. /**
  42998. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  42999. * Returns the DirectionalLight Shadow projection matrix.
  43000. */
  43001. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  43002. if (this.shadowFrustumSize > 0) {
  43003. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  43004. }
  43005. else {
  43006. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  43007. }
  43008. };
  43009. /**
  43010. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  43011. * Returns the DirectionalLight Shadow projection matrix.
  43012. */
  43013. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  43014. var activeCamera = this.getScene().activeCamera;
  43015. if (!activeCamera) {
  43016. return;
  43017. }
  43018. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  43019. };
  43020. /**
  43021. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  43022. * Returns the DirectionalLight Shadow projection matrix.
  43023. */
  43024. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  43025. var activeCamera = this.getScene().activeCamera;
  43026. if (!activeCamera) {
  43027. return;
  43028. }
  43029. // Check extends
  43030. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  43031. var tempVector3 = BABYLON.Vector3.Zero();
  43032. this._orthoLeft = Number.MAX_VALUE;
  43033. this._orthoRight = Number.MIN_VALUE;
  43034. this._orthoTop = Number.MIN_VALUE;
  43035. this._orthoBottom = Number.MAX_VALUE;
  43036. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  43037. var mesh = renderList[meshIndex];
  43038. if (!mesh) {
  43039. continue;
  43040. }
  43041. var boundingInfo = mesh.getBoundingInfo();
  43042. var boundingBox = boundingInfo.boundingBox;
  43043. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  43044. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  43045. if (tempVector3.x < this._orthoLeft)
  43046. this._orthoLeft = tempVector3.x;
  43047. if (tempVector3.y < this._orthoBottom)
  43048. this._orthoBottom = tempVector3.y;
  43049. if (tempVector3.x > this._orthoRight)
  43050. this._orthoRight = tempVector3.x;
  43051. if (tempVector3.y > this._orthoTop)
  43052. this._orthoTop = tempVector3.y;
  43053. }
  43054. }
  43055. }
  43056. var xOffset = this._orthoRight - this._orthoLeft;
  43057. var yOffset = this._orthoTop - this._orthoBottom;
  43058. 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);
  43059. };
  43060. DirectionalLight.prototype._buildUniformLayout = function () {
  43061. this._uniformBuffer.addUniform("vLightData", 4);
  43062. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  43063. this._uniformBuffer.addUniform("vLightSpecular", 3);
  43064. this._uniformBuffer.addUniform("shadowsInfo", 3);
  43065. this._uniformBuffer.addUniform("depthValues", 2);
  43066. this._uniformBuffer.create();
  43067. };
  43068. /**
  43069. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  43070. * Returns the DirectionalLight.
  43071. */
  43072. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  43073. if (this.computeTransformedInformation()) {
  43074. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  43075. return this;
  43076. }
  43077. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  43078. return this;
  43079. };
  43080. /**
  43081. * Gets the minZ used for shadow according to both the scene and the light.
  43082. *
  43083. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  43084. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  43085. * @param activeCamera
  43086. */
  43087. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  43088. return 1;
  43089. };
  43090. /**
  43091. * Gets the maxZ used for shadow according to both the scene and the light.
  43092. *
  43093. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  43094. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  43095. * @param activeCamera
  43096. */
  43097. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  43098. return 1;
  43099. };
  43100. __decorate([
  43101. BABYLON.serialize()
  43102. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  43103. __decorate([
  43104. BABYLON.serialize()
  43105. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  43106. __decorate([
  43107. BABYLON.serialize()
  43108. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  43109. return DirectionalLight;
  43110. }(BABYLON.ShadowLight));
  43111. BABYLON.DirectionalLight = DirectionalLight;
  43112. })(BABYLON || (BABYLON = {}));
  43113. //# sourceMappingURL=babylon.directionalLight.js.map
  43114. var BABYLON;
  43115. (function (BABYLON) {
  43116. var SpotLight = /** @class */ (function (_super) {
  43117. __extends(SpotLight, _super);
  43118. /**
  43119. * Creates a SpotLight object in the scene with the passed parameters :
  43120. * - `position` (Vector3) is the initial SpotLight position,
  43121. * - `direction` (Vector3) is the initial SpotLight direction,
  43122. * - `angle` (float, in radians) is the spot light cone angle,
  43123. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  43124. * A spot light is a simply light oriented cone.
  43125. * It can cast shadows.
  43126. * Documentation : http://doc.babylonjs.com/tutorials/lights
  43127. */
  43128. function SpotLight(name, position, direction, angle, exponent, scene) {
  43129. var _this = _super.call(this, name, scene) || this;
  43130. _this.position = position;
  43131. _this.direction = direction;
  43132. _this.angle = angle;
  43133. _this.exponent = exponent;
  43134. return _this;
  43135. }
  43136. Object.defineProperty(SpotLight.prototype, "angle", {
  43137. get: function () {
  43138. return this._angle;
  43139. },
  43140. set: function (value) {
  43141. this._angle = value;
  43142. this.forceProjectionMatrixCompute();
  43143. },
  43144. enumerable: true,
  43145. configurable: true
  43146. });
  43147. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  43148. get: function () {
  43149. return this._shadowAngleScale;
  43150. },
  43151. /**
  43152. * Allows scaling the angle of the light for shadow generation only.
  43153. */
  43154. set: function (value) {
  43155. this._shadowAngleScale = value;
  43156. this.forceProjectionMatrixCompute();
  43157. },
  43158. enumerable: true,
  43159. configurable: true
  43160. });
  43161. /**
  43162. * Returns the string "SpotLight".
  43163. */
  43164. SpotLight.prototype.getClassName = function () {
  43165. return "SpotLight";
  43166. };
  43167. /**
  43168. * Returns the integer 2.
  43169. */
  43170. SpotLight.prototype.getTypeID = function () {
  43171. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  43172. };
  43173. /**
  43174. * 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.
  43175. * Returns the SpotLight.
  43176. */
  43177. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  43178. var activeCamera = this.getScene().activeCamera;
  43179. if (!activeCamera) {
  43180. return;
  43181. }
  43182. this._shadowAngleScale = this._shadowAngleScale || 1;
  43183. var angle = this._shadowAngleScale * this._angle;
  43184. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  43185. };
  43186. SpotLight.prototype._buildUniformLayout = function () {
  43187. this._uniformBuffer.addUniform("vLightData", 4);
  43188. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  43189. this._uniformBuffer.addUniform("vLightSpecular", 3);
  43190. this._uniformBuffer.addUniform("vLightDirection", 3);
  43191. this._uniformBuffer.addUniform("shadowsInfo", 3);
  43192. this._uniformBuffer.addUniform("depthValues", 2);
  43193. this._uniformBuffer.create();
  43194. };
  43195. /**
  43196. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  43197. * Return the SpotLight.
  43198. */
  43199. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  43200. var normalizeDirection;
  43201. if (this.computeTransformedInformation()) {
  43202. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  43203. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  43204. }
  43205. else {
  43206. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  43207. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  43208. }
  43209. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  43210. return this;
  43211. };
  43212. __decorate([
  43213. BABYLON.serialize()
  43214. ], SpotLight.prototype, "angle", null);
  43215. __decorate([
  43216. BABYLON.serialize()
  43217. /**
  43218. * Allows scaling the angle of the light for shadow generation only.
  43219. */
  43220. ], SpotLight.prototype, "shadowAngleScale", null);
  43221. __decorate([
  43222. BABYLON.serialize()
  43223. ], SpotLight.prototype, "exponent", void 0);
  43224. return SpotLight;
  43225. }(BABYLON.ShadowLight));
  43226. BABYLON.SpotLight = SpotLight;
  43227. })(BABYLON || (BABYLON = {}));
  43228. //# sourceMappingURL=babylon.spotLight.js.map
  43229. var BABYLON;
  43230. (function (BABYLON) {
  43231. var AnimationRange = /** @class */ (function () {
  43232. function AnimationRange(name, from, to) {
  43233. this.name = name;
  43234. this.from = from;
  43235. this.to = to;
  43236. }
  43237. AnimationRange.prototype.clone = function () {
  43238. return new AnimationRange(this.name, this.from, this.to);
  43239. };
  43240. return AnimationRange;
  43241. }());
  43242. BABYLON.AnimationRange = AnimationRange;
  43243. /**
  43244. * Composed of a frame, and an action function
  43245. */
  43246. var AnimationEvent = /** @class */ (function () {
  43247. function AnimationEvent(frame, action, onlyOnce) {
  43248. this.frame = frame;
  43249. this.action = action;
  43250. this.onlyOnce = onlyOnce;
  43251. this.isDone = false;
  43252. }
  43253. return AnimationEvent;
  43254. }());
  43255. BABYLON.AnimationEvent = AnimationEvent;
  43256. var PathCursor = /** @class */ (function () {
  43257. function PathCursor(path) {
  43258. this.path = path;
  43259. this._onchange = new Array();
  43260. this.value = 0;
  43261. this.animations = new Array();
  43262. }
  43263. PathCursor.prototype.getPoint = function () {
  43264. var point = this.path.getPointAtLengthPosition(this.value);
  43265. return new BABYLON.Vector3(point.x, 0, point.y);
  43266. };
  43267. PathCursor.prototype.moveAhead = function (step) {
  43268. if (step === void 0) { step = 0.002; }
  43269. this.move(step);
  43270. return this;
  43271. };
  43272. PathCursor.prototype.moveBack = function (step) {
  43273. if (step === void 0) { step = 0.002; }
  43274. this.move(-step);
  43275. return this;
  43276. };
  43277. PathCursor.prototype.move = function (step) {
  43278. if (Math.abs(step) > 1) {
  43279. throw "step size should be less than 1.";
  43280. }
  43281. this.value += step;
  43282. this.ensureLimits();
  43283. this.raiseOnChange();
  43284. return this;
  43285. };
  43286. PathCursor.prototype.ensureLimits = function () {
  43287. while (this.value > 1) {
  43288. this.value -= 1;
  43289. }
  43290. while (this.value < 0) {
  43291. this.value += 1;
  43292. }
  43293. return this;
  43294. };
  43295. // used by animation engine
  43296. PathCursor.prototype.raiseOnChange = function () {
  43297. var _this = this;
  43298. this._onchange.forEach(function (f) { return f(_this); });
  43299. return this;
  43300. };
  43301. PathCursor.prototype.onchange = function (f) {
  43302. this._onchange.push(f);
  43303. return this;
  43304. };
  43305. return PathCursor;
  43306. }());
  43307. BABYLON.PathCursor = PathCursor;
  43308. var AnimationKeyInterpolation;
  43309. (function (AnimationKeyInterpolation) {
  43310. /**
  43311. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  43312. */
  43313. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  43314. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  43315. var Animation = /** @class */ (function () {
  43316. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  43317. this.name = name;
  43318. this.targetProperty = targetProperty;
  43319. this.framePerSecond = framePerSecond;
  43320. this.dataType = dataType;
  43321. this.loopMode = loopMode;
  43322. this.enableBlending = enableBlending;
  43323. this._runtimeAnimations = new Array();
  43324. // The set of event that will be linked to this animation
  43325. this._events = new Array();
  43326. this.blendingSpeed = 0.01;
  43327. this._ranges = {};
  43328. this.targetPropertyPath = targetProperty.split(".");
  43329. this.dataType = dataType;
  43330. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  43331. }
  43332. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  43333. var dataType = undefined;
  43334. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  43335. dataType = Animation.ANIMATIONTYPE_FLOAT;
  43336. }
  43337. else if (from instanceof BABYLON.Quaternion) {
  43338. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  43339. }
  43340. else if (from instanceof BABYLON.Vector3) {
  43341. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  43342. }
  43343. else if (from instanceof BABYLON.Vector2) {
  43344. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  43345. }
  43346. else if (from instanceof BABYLON.Color3) {
  43347. dataType = Animation.ANIMATIONTYPE_COLOR3;
  43348. }
  43349. else if (from instanceof BABYLON.Size) {
  43350. dataType = Animation.ANIMATIONTYPE_SIZE;
  43351. }
  43352. if (dataType == undefined) {
  43353. return null;
  43354. }
  43355. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  43356. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  43357. animation.setKeys(keys);
  43358. if (easingFunction !== undefined) {
  43359. animation.setEasingFunction(easingFunction);
  43360. }
  43361. return animation;
  43362. };
  43363. /**
  43364. * Sets up an animation.
  43365. * @param property the property to animate
  43366. * @param animationType the animation type to apply
  43367. * @param easingFunction the easing function used in the animation
  43368. * @returns The created animation
  43369. */
  43370. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  43371. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  43372. animation.setEasingFunction(easingFunction);
  43373. return animation;
  43374. };
  43375. /**
  43376. * Create and start an animation on a node
  43377. * @param {string} name defines the name of the global animation that will be run on all nodes
  43378. * @param {BABYLON.Node} node defines the root node where the animation will take place
  43379. * @param {string} targetProperty defines property to animate
  43380. * @param {number} framePerSecond defines the number of frame per second yo use
  43381. * @param {number} totalFrame defines the number of frames in total
  43382. * @param {any} from defines the initial value
  43383. * @param {any} to defines the final value
  43384. * @param {number} loopMode defines which loop mode you want to use (off by default)
  43385. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  43386. * @param onAnimationEnd defines the callback to call when animation end
  43387. * @returns the animatable created for this animation
  43388. */
  43389. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  43390. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  43391. if (!animation) {
  43392. return null;
  43393. }
  43394. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  43395. };
  43396. /**
  43397. * Create and start an animation on a node and its descendants
  43398. * @param {string} name defines the name of the global animation that will be run on all nodes
  43399. * @param {BABYLON.Node} node defines the root node where the animation will take place
  43400. * @param {boolean} directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used.
  43401. * @param {string} targetProperty defines property to animate
  43402. * @param {number} framePerSecond defines the number of frame per second yo use
  43403. * @param {number} totalFrame defines the number of frames in total
  43404. * @param {any} from defines the initial value
  43405. * @param {any} to defines the final value
  43406. * @param {number} loopMode defines which loop mode you want to use (off by default)
  43407. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  43408. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  43409. * @returns the list of animatables created for all nodes
  43410. * @example https://www.babylonjs-playground.com/#MH0VLI
  43411. */
  43412. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  43413. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  43414. if (!animation) {
  43415. return null;
  43416. }
  43417. var scene = node.getScene();
  43418. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  43419. };
  43420. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  43421. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  43422. if (!animation) {
  43423. return null;
  43424. }
  43425. node.animations.push(animation);
  43426. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  43427. };
  43428. /**
  43429. * Transition property of the Camera to the target Value.
  43430. * @param property The property to transition
  43431. * @param targetValue The target Value of the property
  43432. * @param host The object where the property to animate belongs
  43433. * @param scene Scene used to run the animation
  43434. * @param frameRate Framerate (in frame/s) to use
  43435. * @param transition The transition type we want to use
  43436. * @param duration The duration of the animation, in milliseconds
  43437. * @param onAnimationEnd Call back trigger at the end of the animation.
  43438. */
  43439. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  43440. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  43441. if (duration <= 0) {
  43442. host[property] = targetValue;
  43443. if (onAnimationEnd) {
  43444. onAnimationEnd();
  43445. }
  43446. return null;
  43447. }
  43448. var endFrame = frameRate * (duration / 1000);
  43449. transition.setKeys([{
  43450. frame: 0,
  43451. value: host[property].clone ? host[property].clone() : host[property]
  43452. },
  43453. {
  43454. frame: endFrame,
  43455. value: targetValue
  43456. }]);
  43457. if (!host.animations) {
  43458. host.animations = [];
  43459. }
  43460. host.animations.push(transition);
  43461. var animation = scene.beginAnimation(host, 0, endFrame, false);
  43462. animation.onAnimationEnd = onAnimationEnd;
  43463. return animation;
  43464. };
  43465. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  43466. /**
  43467. * Return the array of runtime animations currently using this animation
  43468. */
  43469. get: function () {
  43470. return this._runtimeAnimations;
  43471. },
  43472. enumerable: true,
  43473. configurable: true
  43474. });
  43475. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  43476. get: function () {
  43477. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  43478. var runtimeAnimation = _a[_i];
  43479. if (!runtimeAnimation.isStopped) {
  43480. return true;
  43481. }
  43482. }
  43483. return false;
  43484. },
  43485. enumerable: true,
  43486. configurable: true
  43487. });
  43488. // Methods
  43489. /**
  43490. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  43491. */
  43492. Animation.prototype.toString = function (fullDetails) {
  43493. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  43494. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  43495. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  43496. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  43497. if (fullDetails) {
  43498. ret += ", Ranges: {";
  43499. var first = true;
  43500. for (var name in this._ranges) {
  43501. if (first) {
  43502. ret += ", ";
  43503. first = false;
  43504. }
  43505. ret += name;
  43506. }
  43507. ret += "}";
  43508. }
  43509. return ret;
  43510. };
  43511. /**
  43512. * Add an event to this animation.
  43513. */
  43514. Animation.prototype.addEvent = function (event) {
  43515. this._events.push(event);
  43516. };
  43517. /**
  43518. * Remove all events found at the given frame
  43519. * @param frame
  43520. */
  43521. Animation.prototype.removeEvents = function (frame) {
  43522. for (var index = 0; index < this._events.length; index++) {
  43523. if (this._events[index].frame === frame) {
  43524. this._events.splice(index, 1);
  43525. index--;
  43526. }
  43527. }
  43528. };
  43529. Animation.prototype.getEvents = function () {
  43530. return this._events;
  43531. };
  43532. Animation.prototype.createRange = function (name, from, to) {
  43533. // check name not already in use; could happen for bones after serialized
  43534. if (!this._ranges[name]) {
  43535. this._ranges[name] = new AnimationRange(name, from, to);
  43536. }
  43537. };
  43538. Animation.prototype.deleteRange = function (name, deleteFrames) {
  43539. if (deleteFrames === void 0) { deleteFrames = true; }
  43540. var range = this._ranges[name];
  43541. if (!range) {
  43542. return;
  43543. }
  43544. if (deleteFrames) {
  43545. var from = range.from;
  43546. var to = range.to;
  43547. // this loop MUST go high to low for multiple splices to work
  43548. for (var key = this._keys.length - 1; key >= 0; key--) {
  43549. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  43550. this._keys.splice(key, 1);
  43551. }
  43552. }
  43553. }
  43554. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  43555. };
  43556. Animation.prototype.getRange = function (name) {
  43557. return this._ranges[name];
  43558. };
  43559. Animation.prototype.getKeys = function () {
  43560. return this._keys;
  43561. };
  43562. Animation.prototype.getHighestFrame = function () {
  43563. var ret = 0;
  43564. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  43565. if (ret < this._keys[key].frame) {
  43566. ret = this._keys[key].frame;
  43567. }
  43568. }
  43569. return ret;
  43570. };
  43571. Animation.prototype.getEasingFunction = function () {
  43572. return this._easingFunction;
  43573. };
  43574. Animation.prototype.setEasingFunction = function (easingFunction) {
  43575. this._easingFunction = easingFunction;
  43576. };
  43577. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  43578. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  43579. };
  43580. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  43581. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  43582. };
  43583. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  43584. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  43585. };
  43586. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  43587. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  43588. };
  43589. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  43590. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  43591. };
  43592. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  43593. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  43594. };
  43595. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  43596. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  43597. };
  43598. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  43599. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  43600. };
  43601. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  43602. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  43603. };
  43604. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  43605. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  43606. };
  43607. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  43608. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  43609. };
  43610. Animation.prototype.clone = function () {
  43611. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  43612. clone.enableBlending = this.enableBlending;
  43613. clone.blendingSpeed = this.blendingSpeed;
  43614. if (this._keys) {
  43615. clone.setKeys(this._keys);
  43616. }
  43617. if (this._ranges) {
  43618. clone._ranges = {};
  43619. for (var name in this._ranges) {
  43620. var range = this._ranges[name];
  43621. if (!range) {
  43622. continue;
  43623. }
  43624. clone._ranges[name] = range.clone();
  43625. }
  43626. }
  43627. return clone;
  43628. };
  43629. Animation.prototype.setKeys = function (values) {
  43630. this._keys = values.slice(0);
  43631. };
  43632. Animation.prototype.serialize = function () {
  43633. var serializationObject = {};
  43634. serializationObject.name = this.name;
  43635. serializationObject.property = this.targetProperty;
  43636. serializationObject.framePerSecond = this.framePerSecond;
  43637. serializationObject.dataType = this.dataType;
  43638. serializationObject.loopBehavior = this.loopMode;
  43639. serializationObject.enableBlending = this.enableBlending;
  43640. serializationObject.blendingSpeed = this.blendingSpeed;
  43641. var dataType = this.dataType;
  43642. serializationObject.keys = [];
  43643. var keys = this.getKeys();
  43644. for (var index = 0; index < keys.length; index++) {
  43645. var animationKey = keys[index];
  43646. var key = {};
  43647. key.frame = animationKey.frame;
  43648. switch (dataType) {
  43649. case Animation.ANIMATIONTYPE_FLOAT:
  43650. key.values = [animationKey.value];
  43651. break;
  43652. case Animation.ANIMATIONTYPE_QUATERNION:
  43653. case Animation.ANIMATIONTYPE_MATRIX:
  43654. case Animation.ANIMATIONTYPE_VECTOR3:
  43655. case Animation.ANIMATIONTYPE_COLOR3:
  43656. key.values = animationKey.value.asArray();
  43657. break;
  43658. }
  43659. serializationObject.keys.push(key);
  43660. }
  43661. serializationObject.ranges = [];
  43662. for (var name in this._ranges) {
  43663. var source = this._ranges[name];
  43664. if (!source) {
  43665. continue;
  43666. }
  43667. var range = {};
  43668. range.name = name;
  43669. range.from = source.from;
  43670. range.to = source.to;
  43671. serializationObject.ranges.push(range);
  43672. }
  43673. return serializationObject;
  43674. };
  43675. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  43676. get: function () {
  43677. return Animation._ANIMATIONTYPE_FLOAT;
  43678. },
  43679. enumerable: true,
  43680. configurable: true
  43681. });
  43682. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  43683. get: function () {
  43684. return Animation._ANIMATIONTYPE_VECTOR3;
  43685. },
  43686. enumerable: true,
  43687. configurable: true
  43688. });
  43689. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  43690. get: function () {
  43691. return Animation._ANIMATIONTYPE_VECTOR2;
  43692. },
  43693. enumerable: true,
  43694. configurable: true
  43695. });
  43696. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  43697. get: function () {
  43698. return Animation._ANIMATIONTYPE_SIZE;
  43699. },
  43700. enumerable: true,
  43701. configurable: true
  43702. });
  43703. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  43704. get: function () {
  43705. return Animation._ANIMATIONTYPE_QUATERNION;
  43706. },
  43707. enumerable: true,
  43708. configurable: true
  43709. });
  43710. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  43711. get: function () {
  43712. return Animation._ANIMATIONTYPE_MATRIX;
  43713. },
  43714. enumerable: true,
  43715. configurable: true
  43716. });
  43717. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  43718. get: function () {
  43719. return Animation._ANIMATIONTYPE_COLOR3;
  43720. },
  43721. enumerable: true,
  43722. configurable: true
  43723. });
  43724. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  43725. get: function () {
  43726. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  43727. },
  43728. enumerable: true,
  43729. configurable: true
  43730. });
  43731. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  43732. get: function () {
  43733. return Animation._ANIMATIONLOOPMODE_CYCLE;
  43734. },
  43735. enumerable: true,
  43736. configurable: true
  43737. });
  43738. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  43739. get: function () {
  43740. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  43741. },
  43742. enumerable: true,
  43743. configurable: true
  43744. });
  43745. Animation.Parse = function (parsedAnimation) {
  43746. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  43747. var dataType = parsedAnimation.dataType;
  43748. var keys = [];
  43749. var data;
  43750. var index;
  43751. if (parsedAnimation.enableBlending) {
  43752. animation.enableBlending = parsedAnimation.enableBlending;
  43753. }
  43754. if (parsedAnimation.blendingSpeed) {
  43755. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  43756. }
  43757. for (index = 0; index < parsedAnimation.keys.length; index++) {
  43758. var key = parsedAnimation.keys[index];
  43759. var inTangent;
  43760. var outTangent;
  43761. switch (dataType) {
  43762. case Animation.ANIMATIONTYPE_FLOAT:
  43763. data = key.values[0];
  43764. if (key.values.length >= 1) {
  43765. inTangent = key.values[1];
  43766. }
  43767. if (key.values.length >= 2) {
  43768. outTangent = key.values[2];
  43769. }
  43770. break;
  43771. case Animation.ANIMATIONTYPE_QUATERNION:
  43772. data = BABYLON.Quaternion.FromArray(key.values);
  43773. if (key.values.length >= 8) {
  43774. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  43775. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  43776. inTangent = _inTangent;
  43777. }
  43778. }
  43779. if (key.values.length >= 12) {
  43780. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  43781. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  43782. outTangent = _outTangent;
  43783. }
  43784. }
  43785. break;
  43786. case Animation.ANIMATIONTYPE_MATRIX:
  43787. data = BABYLON.Matrix.FromArray(key.values);
  43788. break;
  43789. case Animation.ANIMATIONTYPE_COLOR3:
  43790. data = BABYLON.Color3.FromArray(key.values);
  43791. break;
  43792. case Animation.ANIMATIONTYPE_VECTOR3:
  43793. default:
  43794. data = BABYLON.Vector3.FromArray(key.values);
  43795. break;
  43796. }
  43797. var keyData = {};
  43798. keyData.frame = key.frame;
  43799. keyData.value = data;
  43800. if (inTangent != undefined) {
  43801. keyData.inTangent = inTangent;
  43802. }
  43803. if (outTangent != undefined) {
  43804. keyData.outTangent = outTangent;
  43805. }
  43806. keys.push(keyData);
  43807. }
  43808. animation.setKeys(keys);
  43809. if (parsedAnimation.ranges) {
  43810. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  43811. data = parsedAnimation.ranges[index];
  43812. animation.createRange(data.name, data.from, data.to);
  43813. }
  43814. }
  43815. return animation;
  43816. };
  43817. Animation.AppendSerializedAnimations = function (source, destination) {
  43818. if (source.animations) {
  43819. destination.animations = [];
  43820. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  43821. var animation = source.animations[animationIndex];
  43822. destination.animations.push(animation.serialize());
  43823. }
  43824. }
  43825. };
  43826. Animation.AllowMatricesInterpolation = false;
  43827. // Statics
  43828. Animation._ANIMATIONTYPE_FLOAT = 0;
  43829. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  43830. Animation._ANIMATIONTYPE_QUATERNION = 2;
  43831. Animation._ANIMATIONTYPE_MATRIX = 3;
  43832. Animation._ANIMATIONTYPE_COLOR3 = 4;
  43833. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  43834. Animation._ANIMATIONTYPE_SIZE = 6;
  43835. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  43836. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  43837. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  43838. return Animation;
  43839. }());
  43840. BABYLON.Animation = Animation;
  43841. })(BABYLON || (BABYLON = {}));
  43842. //# sourceMappingURL=babylon.animation.js.map
  43843. var BABYLON;
  43844. (function (BABYLON) {
  43845. /**
  43846. * This class defines the direct association between an animation and a target
  43847. */
  43848. var TargetedAnimation = /** @class */ (function () {
  43849. function TargetedAnimation() {
  43850. }
  43851. return TargetedAnimation;
  43852. }());
  43853. BABYLON.TargetedAnimation = TargetedAnimation;
  43854. /**
  43855. * Use this class to create coordinated animations on multiple targets
  43856. */
  43857. var AnimationGroup = /** @class */ (function () {
  43858. function AnimationGroup(name, scene) {
  43859. if (scene === void 0) { scene = null; }
  43860. this.name = name;
  43861. this._targetedAnimations = new Array();
  43862. this._animatables = new Array();
  43863. this._from = Number.MAX_VALUE;
  43864. this._to = -Number.MAX_VALUE;
  43865. this._speedRatio = 1;
  43866. this.onAnimationEndObservable = new BABYLON.Observable();
  43867. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  43868. this._scene.animationGroups.push(this);
  43869. }
  43870. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  43871. /**
  43872. * Define if the animations are started
  43873. */
  43874. get: function () {
  43875. return this._isStarted;
  43876. },
  43877. enumerable: true,
  43878. configurable: true
  43879. });
  43880. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  43881. /**
  43882. * Gets or sets the speed ratio to use for all animations
  43883. */
  43884. get: function () {
  43885. return this._speedRatio;
  43886. },
  43887. /**
  43888. * Gets or sets the speed ratio to use for all animations
  43889. */
  43890. set: function (value) {
  43891. if (this._speedRatio === value) {
  43892. return;
  43893. }
  43894. this._speedRatio = value;
  43895. for (var index = 0; index < this._animatables.length; index++) {
  43896. var animatable = this._animatables[index];
  43897. animatable.speedRatio = this._speedRatio;
  43898. }
  43899. },
  43900. enumerable: true,
  43901. configurable: true
  43902. });
  43903. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  43904. /**
  43905. * Gets the targeted animations for this animation group
  43906. */
  43907. get: function () {
  43908. return this._targetedAnimations;
  43909. },
  43910. enumerable: true,
  43911. configurable: true
  43912. });
  43913. /**
  43914. * Add an animation (with its target) in the group
  43915. * @param animation defines the animation we want to add
  43916. * @param target defines the target of the animation
  43917. * @returns the {BABYLON.TargetedAnimation} object
  43918. */
  43919. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  43920. var targetedAnimation = {
  43921. animation: animation,
  43922. target: target
  43923. };
  43924. var keys = animation.getKeys();
  43925. if (this._from > keys[0].frame) {
  43926. this._from = keys[0].frame;
  43927. }
  43928. if (this._to < keys[keys.length - 1].frame) {
  43929. this._to = keys[keys.length - 1].frame;
  43930. }
  43931. this._targetedAnimations.push(targetedAnimation);
  43932. return targetedAnimation;
  43933. };
  43934. /**
  43935. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  43936. * It can add constant keys at begin or end
  43937. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  43938. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  43939. */
  43940. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  43941. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  43942. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  43943. beginFrame = Math.max(beginFrame, this._from);
  43944. endFrame = Math.min(endFrame, this._to);
  43945. for (var index = 0; index < this._targetedAnimations.length; index++) {
  43946. var targetedAnimation = this._targetedAnimations[index];
  43947. var keys = targetedAnimation.animation.getKeys();
  43948. var startKey = keys[0];
  43949. var endKey = keys[keys.length - 1];
  43950. if (startKey.frame > beginFrame) {
  43951. var newKey = {
  43952. frame: beginFrame,
  43953. value: startKey.value,
  43954. inTangent: startKey.inTangent,
  43955. outTangent: startKey.outTangent,
  43956. interpolation: startKey.interpolation
  43957. };
  43958. keys.splice(0, 0, newKey);
  43959. }
  43960. if (endKey.frame < endFrame) {
  43961. var newKey = {
  43962. frame: endFrame,
  43963. value: endKey.value,
  43964. inTangent: endKey.outTangent,
  43965. outTangent: endKey.outTangent,
  43966. interpolation: endKey.interpolation
  43967. };
  43968. keys.push(newKey);
  43969. }
  43970. }
  43971. return this;
  43972. };
  43973. /**
  43974. * Start all animations on given targets
  43975. * @param loop defines if animations must loop
  43976. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  43977. */
  43978. AnimationGroup.prototype.start = function (loop, speedRatio) {
  43979. var _this = this;
  43980. if (loop === void 0) { loop = false; }
  43981. if (speedRatio === void 0) { speedRatio = 1; }
  43982. if (this._isStarted || this._targetedAnimations.length === 0) {
  43983. return this;
  43984. }
  43985. var _loop_1 = function () {
  43986. var targetedAnimation = this_1._targetedAnimations[index];
  43987. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  43988. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  43989. }));
  43990. };
  43991. var this_1 = this;
  43992. for (var index = 0; index < this._targetedAnimations.length; index++) {
  43993. _loop_1();
  43994. }
  43995. this._speedRatio = speedRatio;
  43996. this._isStarted = true;
  43997. return this;
  43998. };
  43999. /**
  44000. * Pause all animations
  44001. */
  44002. AnimationGroup.prototype.pause = function () {
  44003. if (!this._isStarted) {
  44004. return this;
  44005. }
  44006. for (var index = 0; index < this._animatables.length; index++) {
  44007. var animatable = this._animatables[index];
  44008. animatable.pause();
  44009. }
  44010. return this;
  44011. };
  44012. /**
  44013. * Play all animations to initial state
  44014. * This function will start() the animations if they were not started or will restart() them if they were paused
  44015. * @param loop defines if animations must loop
  44016. */
  44017. AnimationGroup.prototype.play = function (loop) {
  44018. if (this.isStarted) {
  44019. if (loop !== undefined) {
  44020. for (var index = 0; index < this._animatables.length; index++) {
  44021. var animatable = this._animatables[index];
  44022. animatable.loopAnimation = loop;
  44023. }
  44024. }
  44025. this.restart();
  44026. }
  44027. else {
  44028. this.start(loop, this._speedRatio);
  44029. }
  44030. return this;
  44031. };
  44032. /**
  44033. * Reset all animations to initial state
  44034. */
  44035. AnimationGroup.prototype.reset = function () {
  44036. if (!this._isStarted) {
  44037. return this;
  44038. }
  44039. for (var index = 0; index < this._animatables.length; index++) {
  44040. var animatable = this._animatables[index];
  44041. animatable.reset();
  44042. }
  44043. return this;
  44044. };
  44045. /**
  44046. * Restart animations from key 0
  44047. */
  44048. AnimationGroup.prototype.restart = function () {
  44049. if (!this._isStarted) {
  44050. return this;
  44051. }
  44052. for (var index = 0; index < this._animatables.length; index++) {
  44053. var animatable = this._animatables[index];
  44054. animatable.restart();
  44055. }
  44056. return this;
  44057. };
  44058. /**
  44059. * Stop all animations
  44060. */
  44061. AnimationGroup.prototype.stop = function () {
  44062. if (!this._isStarted) {
  44063. return this;
  44064. }
  44065. for (var index = 0; index < this._animatables.length; index++) {
  44066. var animatable = this._animatables[index];
  44067. animatable.stop();
  44068. }
  44069. this._isStarted = false;
  44070. return this;
  44071. };
  44072. /**
  44073. * Dispose all associated resources
  44074. */
  44075. AnimationGroup.prototype.dispose = function () {
  44076. this._targetedAnimations = [];
  44077. this._animatables = [];
  44078. var index = this._scene.animationGroups.indexOf(this);
  44079. if (index > -1) {
  44080. this._scene.animationGroups.splice(index, 1);
  44081. }
  44082. };
  44083. return AnimationGroup;
  44084. }());
  44085. BABYLON.AnimationGroup = AnimationGroup;
  44086. })(BABYLON || (BABYLON = {}));
  44087. //# sourceMappingURL=babylon.animationGroup.js.map
  44088. var BABYLON;
  44089. (function (BABYLON) {
  44090. var RuntimeAnimation = /** @class */ (function () {
  44091. function RuntimeAnimation(target, animation) {
  44092. this._offsetsCache = {};
  44093. this._highLimitsCache = {};
  44094. this._stopped = false;
  44095. this._blendingFactor = 0;
  44096. this._ratioOffset = 0;
  44097. this._animation = animation;
  44098. this._target = target;
  44099. animation._runtimeAnimations.push(this);
  44100. }
  44101. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  44102. get: function () {
  44103. return this._animation;
  44104. },
  44105. enumerable: true,
  44106. configurable: true
  44107. });
  44108. RuntimeAnimation.prototype.reset = function () {
  44109. this._offsetsCache = {};
  44110. this._highLimitsCache = {};
  44111. this.currentFrame = 0;
  44112. this._blendingFactor = 0;
  44113. this._originalBlendValue = null;
  44114. };
  44115. RuntimeAnimation.prototype.isStopped = function () {
  44116. return this._stopped;
  44117. };
  44118. RuntimeAnimation.prototype.dispose = function () {
  44119. var index = this._animation.runtimeAnimations.indexOf(this);
  44120. if (index > -1) {
  44121. this._animation.runtimeAnimations.splice(index, 1);
  44122. }
  44123. };
  44124. RuntimeAnimation.prototype._getKeyValue = function (value) {
  44125. if (typeof value === "function") {
  44126. return value();
  44127. }
  44128. return value;
  44129. };
  44130. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  44131. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  44132. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  44133. }
  44134. this.currentFrame = currentFrame;
  44135. var keys = this._animation.getKeys();
  44136. // Try to get a hash to find the right key
  44137. 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));
  44138. if (keys[startKeyIndex].frame >= currentFrame) {
  44139. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  44140. startKeyIndex--;
  44141. }
  44142. }
  44143. for (var key = startKeyIndex; key < keys.length; key++) {
  44144. var endKey = keys[key + 1];
  44145. if (endKey.frame >= currentFrame) {
  44146. var startKey = keys[key];
  44147. var startValue = this._getKeyValue(startKey.value);
  44148. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  44149. return startValue;
  44150. }
  44151. var endValue = this._getKeyValue(endKey.value);
  44152. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  44153. var frameDelta = endKey.frame - startKey.frame;
  44154. // gradient : percent of currentFrame between the frame inf and the frame sup
  44155. var gradient = (currentFrame - startKey.frame) / frameDelta;
  44156. // check for easingFunction and correction of gradient
  44157. var easingFunction = this._animation.getEasingFunction();
  44158. if (easingFunction != null) {
  44159. gradient = easingFunction.ease(gradient);
  44160. }
  44161. switch (this._animation.dataType) {
  44162. // Float
  44163. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  44164. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  44165. switch (loopMode) {
  44166. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  44167. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  44168. return floatValue;
  44169. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  44170. return offsetValue * repeatCount + floatValue;
  44171. }
  44172. break;
  44173. // Quaternion
  44174. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  44175. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  44176. switch (loopMode) {
  44177. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  44178. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  44179. return quatValue;
  44180. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  44181. return quatValue.add(offsetValue.scale(repeatCount));
  44182. }
  44183. return quatValue;
  44184. // Vector3
  44185. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  44186. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  44187. switch (loopMode) {
  44188. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  44189. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  44190. return vec3Value;
  44191. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  44192. return vec3Value.add(offsetValue.scale(repeatCount));
  44193. }
  44194. // Vector2
  44195. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  44196. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  44197. switch (loopMode) {
  44198. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  44199. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  44200. return vec2Value;
  44201. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  44202. return vec2Value.add(offsetValue.scale(repeatCount));
  44203. }
  44204. // Size
  44205. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  44206. switch (loopMode) {
  44207. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  44208. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  44209. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  44210. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  44211. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  44212. }
  44213. // Color3
  44214. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  44215. switch (loopMode) {
  44216. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  44217. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  44218. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  44219. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  44220. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  44221. }
  44222. // Matrix
  44223. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  44224. switch (loopMode) {
  44225. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  44226. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  44227. if (BABYLON.Animation.AllowMatricesInterpolation) {
  44228. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  44229. }
  44230. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  44231. return startValue;
  44232. }
  44233. default:
  44234. break;
  44235. }
  44236. break;
  44237. }
  44238. }
  44239. return this._getKeyValue(keys[keys.length - 1].value);
  44240. };
  44241. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  44242. if (blend === void 0) { blend = false; }
  44243. // Set value
  44244. var path;
  44245. var destination;
  44246. var targetPropertyPath = this._animation.targetPropertyPath;
  44247. if (targetPropertyPath.length > 1) {
  44248. var property = this._target[targetPropertyPath[0]];
  44249. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  44250. property = property[targetPropertyPath[index]];
  44251. }
  44252. path = targetPropertyPath[targetPropertyPath.length - 1];
  44253. destination = property;
  44254. }
  44255. else {
  44256. path = targetPropertyPath[0];
  44257. destination = this._target;
  44258. }
  44259. // Blending
  44260. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  44261. if (!this._originalBlendValue) {
  44262. if (destination[path].clone) {
  44263. this._originalBlendValue = destination[path].clone();
  44264. }
  44265. else {
  44266. this._originalBlendValue = destination[path];
  44267. }
  44268. }
  44269. if (this._originalBlendValue.prototype) {
  44270. if (this._originalBlendValue.prototype.Lerp) {
  44271. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  44272. }
  44273. else {
  44274. destination[path] = currentValue;
  44275. }
  44276. }
  44277. else if (this._originalBlendValue.m) {
  44278. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  44279. }
  44280. else {
  44281. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  44282. }
  44283. this._blendingFactor += this._animation.blendingSpeed;
  44284. }
  44285. else {
  44286. destination[path] = currentValue;
  44287. }
  44288. if (this._target.markAsDirty) {
  44289. this._target.markAsDirty(this._animation.targetProperty);
  44290. }
  44291. };
  44292. RuntimeAnimation.prototype.goToFrame = function (frame) {
  44293. var keys = this._animation.getKeys();
  44294. if (frame < keys[0].frame) {
  44295. frame = keys[0].frame;
  44296. }
  44297. else if (frame > keys[keys.length - 1].frame) {
  44298. frame = keys[keys.length - 1].frame;
  44299. }
  44300. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  44301. this.setValue(currentValue);
  44302. };
  44303. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  44304. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  44305. this._ratioOffset = this._previousRatio - newRatio;
  44306. };
  44307. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  44308. if (blend === void 0) { blend = false; }
  44309. var targetPropertyPath = this._animation.targetPropertyPath;
  44310. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  44311. this._stopped = true;
  44312. return false;
  44313. }
  44314. var returnValue = true;
  44315. var keys = this._animation.getKeys();
  44316. // Adding a start key at frame 0 if missing
  44317. if (keys[0].frame !== 0) {
  44318. var newKey = { frame: 0, value: keys[0].value };
  44319. keys.splice(0, 0, newKey);
  44320. }
  44321. // Check limits
  44322. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  44323. from = keys[0].frame;
  44324. }
  44325. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  44326. to = keys[keys.length - 1].frame;
  44327. }
  44328. //to and from cannot be the same key
  44329. if (from === to) {
  44330. if (from > keys[0].frame) {
  44331. from--;
  44332. }
  44333. else if (to < keys[keys.length - 1].frame) {
  44334. to++;
  44335. }
  44336. }
  44337. // Compute ratio
  44338. var range = to - from;
  44339. var offsetValue;
  44340. // ratio represents the frame delta between from and to
  44341. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  44342. var highLimitValue = 0;
  44343. this._previousDelay = delay;
  44344. this._previousRatio = ratio;
  44345. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  44346. returnValue = false;
  44347. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  44348. }
  44349. else {
  44350. // Get max value if required
  44351. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  44352. var keyOffset = to.toString() + from.toString();
  44353. if (!this._offsetsCache[keyOffset]) {
  44354. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  44355. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  44356. switch (this._animation.dataType) {
  44357. // Float
  44358. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  44359. this._offsetsCache[keyOffset] = toValue - fromValue;
  44360. break;
  44361. // Quaternion
  44362. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  44363. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  44364. break;
  44365. // Vector3
  44366. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  44367. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  44368. // Vector2
  44369. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  44370. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  44371. // Size
  44372. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  44373. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  44374. // Color3
  44375. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  44376. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  44377. default:
  44378. break;
  44379. }
  44380. this._highLimitsCache[keyOffset] = toValue;
  44381. }
  44382. highLimitValue = this._highLimitsCache[keyOffset];
  44383. offsetValue = this._offsetsCache[keyOffset];
  44384. }
  44385. }
  44386. if (offsetValue === undefined) {
  44387. switch (this._animation.dataType) {
  44388. // Float
  44389. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  44390. offsetValue = 0;
  44391. break;
  44392. // Quaternion
  44393. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  44394. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  44395. break;
  44396. // Vector3
  44397. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  44398. offsetValue = BABYLON.Vector3.Zero();
  44399. break;
  44400. // Vector2
  44401. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  44402. offsetValue = BABYLON.Vector2.Zero();
  44403. break;
  44404. // Size
  44405. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  44406. offsetValue = BABYLON.Size.Zero();
  44407. break;
  44408. // Color3
  44409. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  44410. offsetValue = BABYLON.Color3.Black();
  44411. }
  44412. }
  44413. // Compute value
  44414. var repeatCount = (ratio / range) >> 0;
  44415. var currentFrame = returnValue ? from + ratio % range : to;
  44416. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  44417. // Set value
  44418. this.setValue(currentValue);
  44419. // Check events
  44420. var events = this._animation.getEvents();
  44421. for (var index = 0; index < events.length; index++) {
  44422. // Make sure current frame has passed event frame and that event frame is within the current range
  44423. // Also, handle both forward and reverse animations
  44424. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  44425. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  44426. var event = events[index];
  44427. if (!event.isDone) {
  44428. // If event should be done only once, remove it.
  44429. if (event.onlyOnce) {
  44430. events.splice(index, 1);
  44431. index--;
  44432. }
  44433. event.isDone = true;
  44434. event.action();
  44435. } // Don't do anything if the event has already be done.
  44436. }
  44437. else if (events[index].isDone && !events[index].onlyOnce) {
  44438. // reset event, the animation is looping
  44439. events[index].isDone = false;
  44440. }
  44441. }
  44442. if (!returnValue) {
  44443. this._stopped = true;
  44444. }
  44445. return returnValue;
  44446. };
  44447. return RuntimeAnimation;
  44448. }());
  44449. BABYLON.RuntimeAnimation = RuntimeAnimation;
  44450. })(BABYLON || (BABYLON = {}));
  44451. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  44452. var BABYLON;
  44453. (function (BABYLON) {
  44454. var Animatable = /** @class */ (function () {
  44455. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  44456. if (fromFrame === void 0) { fromFrame = 0; }
  44457. if (toFrame === void 0) { toFrame = 100; }
  44458. if (loopAnimation === void 0) { loopAnimation = false; }
  44459. if (speedRatio === void 0) { speedRatio = 1.0; }
  44460. this.target = target;
  44461. this.fromFrame = fromFrame;
  44462. this.toFrame = toFrame;
  44463. this.loopAnimation = loopAnimation;
  44464. this.onAnimationEnd = onAnimationEnd;
  44465. this._localDelayOffset = null;
  44466. this._pausedDelay = null;
  44467. this._runtimeAnimations = new Array();
  44468. this._paused = false;
  44469. this._speedRatio = 1;
  44470. this.animationStarted = false;
  44471. if (animations) {
  44472. this.appendAnimations(target, animations);
  44473. }
  44474. this._speedRatio = speedRatio;
  44475. this._scene = scene;
  44476. scene._activeAnimatables.push(this);
  44477. }
  44478. Object.defineProperty(Animatable.prototype, "speedRatio", {
  44479. get: function () {
  44480. return this._speedRatio;
  44481. },
  44482. set: function (value) {
  44483. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  44484. var animation = this._runtimeAnimations[index];
  44485. animation._prepareForSpeedRatioChange(value);
  44486. }
  44487. this._speedRatio = value;
  44488. },
  44489. enumerable: true,
  44490. configurable: true
  44491. });
  44492. // Methods
  44493. Animatable.prototype.getAnimations = function () {
  44494. return this._runtimeAnimations;
  44495. };
  44496. Animatable.prototype.appendAnimations = function (target, animations) {
  44497. for (var index = 0; index < animations.length; index++) {
  44498. var animation = animations[index];
  44499. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  44500. }
  44501. };
  44502. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  44503. var runtimeAnimations = this._runtimeAnimations;
  44504. for (var index = 0; index < runtimeAnimations.length; index++) {
  44505. if (runtimeAnimations[index].animation.targetProperty === property) {
  44506. return runtimeAnimations[index].animation;
  44507. }
  44508. }
  44509. return null;
  44510. };
  44511. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  44512. var runtimeAnimations = this._runtimeAnimations;
  44513. for (var index = 0; index < runtimeAnimations.length; index++) {
  44514. if (runtimeAnimations[index].animation.targetProperty === property) {
  44515. return runtimeAnimations[index];
  44516. }
  44517. }
  44518. return null;
  44519. };
  44520. Animatable.prototype.reset = function () {
  44521. var runtimeAnimations = this._runtimeAnimations;
  44522. for (var index = 0; index < runtimeAnimations.length; index++) {
  44523. runtimeAnimations[index].reset();
  44524. }
  44525. // Reset to original value
  44526. for (index = 0; index < runtimeAnimations.length; index++) {
  44527. var animation = runtimeAnimations[index];
  44528. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  44529. }
  44530. this._localDelayOffset = null;
  44531. this._pausedDelay = null;
  44532. };
  44533. Animatable.prototype.enableBlending = function (blendingSpeed) {
  44534. var runtimeAnimations = this._runtimeAnimations;
  44535. for (var index = 0; index < runtimeAnimations.length; index++) {
  44536. runtimeAnimations[index].animation.enableBlending = true;
  44537. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  44538. }
  44539. };
  44540. Animatable.prototype.disableBlending = function () {
  44541. var runtimeAnimations = this._runtimeAnimations;
  44542. for (var index = 0; index < runtimeAnimations.length; index++) {
  44543. runtimeAnimations[index].animation.enableBlending = false;
  44544. }
  44545. };
  44546. Animatable.prototype.goToFrame = function (frame) {
  44547. var runtimeAnimations = this._runtimeAnimations;
  44548. if (runtimeAnimations[0]) {
  44549. var fps = runtimeAnimations[0].animation.framePerSecond;
  44550. var currentFrame = runtimeAnimations[0].currentFrame;
  44551. var adjustTime = frame - currentFrame;
  44552. var delay = adjustTime * 1000 / fps;
  44553. if (this._localDelayOffset === null) {
  44554. this._localDelayOffset = 0;
  44555. }
  44556. this._localDelayOffset -= delay;
  44557. }
  44558. for (var index = 0; index < runtimeAnimations.length; index++) {
  44559. runtimeAnimations[index].goToFrame(frame);
  44560. }
  44561. };
  44562. Animatable.prototype.pause = function () {
  44563. if (this._paused) {
  44564. return;
  44565. }
  44566. this._paused = true;
  44567. };
  44568. Animatable.prototype.restart = function () {
  44569. this._paused = false;
  44570. };
  44571. Animatable.prototype.stop = function (animationName) {
  44572. if (animationName) {
  44573. var idx = this._scene._activeAnimatables.indexOf(this);
  44574. if (idx > -1) {
  44575. var runtimeAnimations = this._runtimeAnimations;
  44576. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  44577. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  44578. continue;
  44579. }
  44580. runtimeAnimations[index].dispose();
  44581. runtimeAnimations.splice(index, 1);
  44582. }
  44583. if (runtimeAnimations.length == 0) {
  44584. this._scene._activeAnimatables.splice(idx, 1);
  44585. if (this.onAnimationEnd) {
  44586. this.onAnimationEnd();
  44587. }
  44588. }
  44589. }
  44590. }
  44591. else {
  44592. var index = this._scene._activeAnimatables.indexOf(this);
  44593. if (index > -1) {
  44594. this._scene._activeAnimatables.splice(index, 1);
  44595. var runtimeAnimations = this._runtimeAnimations;
  44596. for (var index = 0; index < runtimeAnimations.length; index++) {
  44597. runtimeAnimations[index].dispose();
  44598. }
  44599. if (this.onAnimationEnd) {
  44600. this.onAnimationEnd();
  44601. }
  44602. }
  44603. }
  44604. };
  44605. Animatable.prototype._animate = function (delay) {
  44606. if (this._paused) {
  44607. this.animationStarted = false;
  44608. if (this._pausedDelay === null) {
  44609. this._pausedDelay = delay;
  44610. }
  44611. return true;
  44612. }
  44613. if (this._localDelayOffset === null) {
  44614. this._localDelayOffset = delay;
  44615. this._pausedDelay = null;
  44616. }
  44617. else if (this._pausedDelay !== null) {
  44618. this._localDelayOffset += delay - this._pausedDelay;
  44619. this._pausedDelay = null;
  44620. }
  44621. // Animating
  44622. var running = false;
  44623. var runtimeAnimations = this._runtimeAnimations;
  44624. var index;
  44625. for (index = 0; index < runtimeAnimations.length; index++) {
  44626. var animation = runtimeAnimations[index];
  44627. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  44628. running = running || isRunning;
  44629. }
  44630. this.animationStarted = running;
  44631. if (!running) {
  44632. // Remove from active animatables
  44633. index = this._scene._activeAnimatables.indexOf(this);
  44634. this._scene._activeAnimatables.splice(index, 1);
  44635. // Dispose all runtime animations
  44636. for (index = 0; index < runtimeAnimations.length; index++) {
  44637. runtimeAnimations[index].dispose();
  44638. }
  44639. }
  44640. if (!running && this.onAnimationEnd) {
  44641. this.onAnimationEnd();
  44642. this.onAnimationEnd = null;
  44643. }
  44644. return running;
  44645. };
  44646. return Animatable;
  44647. }());
  44648. BABYLON.Animatable = Animatable;
  44649. })(BABYLON || (BABYLON = {}));
  44650. //# sourceMappingURL=babylon.animatable.js.map
  44651. var BABYLON;
  44652. (function (BABYLON) {
  44653. var EasingFunction = /** @class */ (function () {
  44654. function EasingFunction() {
  44655. // Properties
  44656. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  44657. }
  44658. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  44659. get: function () {
  44660. return EasingFunction._EASINGMODE_EASEIN;
  44661. },
  44662. enumerable: true,
  44663. configurable: true
  44664. });
  44665. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  44666. get: function () {
  44667. return EasingFunction._EASINGMODE_EASEOUT;
  44668. },
  44669. enumerable: true,
  44670. configurable: true
  44671. });
  44672. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  44673. get: function () {
  44674. return EasingFunction._EASINGMODE_EASEINOUT;
  44675. },
  44676. enumerable: true,
  44677. configurable: true
  44678. });
  44679. EasingFunction.prototype.setEasingMode = function (easingMode) {
  44680. var n = Math.min(Math.max(easingMode, 0), 2);
  44681. this._easingMode = n;
  44682. };
  44683. EasingFunction.prototype.getEasingMode = function () {
  44684. return this._easingMode;
  44685. };
  44686. EasingFunction.prototype.easeInCore = function (gradient) {
  44687. throw new Error('You must implement this method');
  44688. };
  44689. EasingFunction.prototype.ease = function (gradient) {
  44690. switch (this._easingMode) {
  44691. case EasingFunction.EASINGMODE_EASEIN:
  44692. return this.easeInCore(gradient);
  44693. case EasingFunction.EASINGMODE_EASEOUT:
  44694. return (1 - this.easeInCore(1 - gradient));
  44695. }
  44696. if (gradient >= 0.5) {
  44697. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  44698. }
  44699. return (this.easeInCore(gradient * 2) * 0.5);
  44700. };
  44701. //Statics
  44702. EasingFunction._EASINGMODE_EASEIN = 0;
  44703. EasingFunction._EASINGMODE_EASEOUT = 1;
  44704. EasingFunction._EASINGMODE_EASEINOUT = 2;
  44705. return EasingFunction;
  44706. }());
  44707. BABYLON.EasingFunction = EasingFunction;
  44708. var CircleEase = /** @class */ (function (_super) {
  44709. __extends(CircleEase, _super);
  44710. function CircleEase() {
  44711. return _super !== null && _super.apply(this, arguments) || this;
  44712. }
  44713. CircleEase.prototype.easeInCore = function (gradient) {
  44714. gradient = Math.max(0, Math.min(1, gradient));
  44715. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  44716. };
  44717. return CircleEase;
  44718. }(EasingFunction));
  44719. BABYLON.CircleEase = CircleEase;
  44720. var BackEase = /** @class */ (function (_super) {
  44721. __extends(BackEase, _super);
  44722. function BackEase(amplitude) {
  44723. if (amplitude === void 0) { amplitude = 1; }
  44724. var _this = _super.call(this) || this;
  44725. _this.amplitude = amplitude;
  44726. return _this;
  44727. }
  44728. BackEase.prototype.easeInCore = function (gradient) {
  44729. var num = Math.max(0, this.amplitude);
  44730. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  44731. };
  44732. return BackEase;
  44733. }(EasingFunction));
  44734. BABYLON.BackEase = BackEase;
  44735. var BounceEase = /** @class */ (function (_super) {
  44736. __extends(BounceEase, _super);
  44737. function BounceEase(bounces, bounciness) {
  44738. if (bounces === void 0) { bounces = 3; }
  44739. if (bounciness === void 0) { bounciness = 2; }
  44740. var _this = _super.call(this) || this;
  44741. _this.bounces = bounces;
  44742. _this.bounciness = bounciness;
  44743. return _this;
  44744. }
  44745. BounceEase.prototype.easeInCore = function (gradient) {
  44746. var y = Math.max(0.0, this.bounces);
  44747. var bounciness = this.bounciness;
  44748. if (bounciness <= 1.0) {
  44749. bounciness = 1.001;
  44750. }
  44751. var num9 = Math.pow(bounciness, y);
  44752. var num5 = 1.0 - bounciness;
  44753. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  44754. var num15 = gradient * num4;
  44755. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  44756. var num3 = Math.floor(num65);
  44757. var num13 = num3 + 1.0;
  44758. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  44759. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  44760. var num7 = (num8 + num12) * 0.5;
  44761. var num6 = gradient - num7;
  44762. var num2 = num7 - num8;
  44763. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  44764. };
  44765. return BounceEase;
  44766. }(EasingFunction));
  44767. BABYLON.BounceEase = BounceEase;
  44768. var CubicEase = /** @class */ (function (_super) {
  44769. __extends(CubicEase, _super);
  44770. function CubicEase() {
  44771. return _super !== null && _super.apply(this, arguments) || this;
  44772. }
  44773. CubicEase.prototype.easeInCore = function (gradient) {
  44774. return (gradient * gradient * gradient);
  44775. };
  44776. return CubicEase;
  44777. }(EasingFunction));
  44778. BABYLON.CubicEase = CubicEase;
  44779. var ElasticEase = /** @class */ (function (_super) {
  44780. __extends(ElasticEase, _super);
  44781. function ElasticEase(oscillations, springiness) {
  44782. if (oscillations === void 0) { oscillations = 3; }
  44783. if (springiness === void 0) { springiness = 3; }
  44784. var _this = _super.call(this) || this;
  44785. _this.oscillations = oscillations;
  44786. _this.springiness = springiness;
  44787. return _this;
  44788. }
  44789. ElasticEase.prototype.easeInCore = function (gradient) {
  44790. var num2;
  44791. var num3 = Math.max(0.0, this.oscillations);
  44792. var num = Math.max(0.0, this.springiness);
  44793. if (num == 0) {
  44794. num2 = gradient;
  44795. }
  44796. else {
  44797. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  44798. }
  44799. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  44800. };
  44801. return ElasticEase;
  44802. }(EasingFunction));
  44803. BABYLON.ElasticEase = ElasticEase;
  44804. var ExponentialEase = /** @class */ (function (_super) {
  44805. __extends(ExponentialEase, _super);
  44806. function ExponentialEase(exponent) {
  44807. if (exponent === void 0) { exponent = 2; }
  44808. var _this = _super.call(this) || this;
  44809. _this.exponent = exponent;
  44810. return _this;
  44811. }
  44812. ExponentialEase.prototype.easeInCore = function (gradient) {
  44813. if (this.exponent <= 0) {
  44814. return gradient;
  44815. }
  44816. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  44817. };
  44818. return ExponentialEase;
  44819. }(EasingFunction));
  44820. BABYLON.ExponentialEase = ExponentialEase;
  44821. var PowerEase = /** @class */ (function (_super) {
  44822. __extends(PowerEase, _super);
  44823. function PowerEase(power) {
  44824. if (power === void 0) { power = 2; }
  44825. var _this = _super.call(this) || this;
  44826. _this.power = power;
  44827. return _this;
  44828. }
  44829. PowerEase.prototype.easeInCore = function (gradient) {
  44830. var y = Math.max(0.0, this.power);
  44831. return Math.pow(gradient, y);
  44832. };
  44833. return PowerEase;
  44834. }(EasingFunction));
  44835. BABYLON.PowerEase = PowerEase;
  44836. var QuadraticEase = /** @class */ (function (_super) {
  44837. __extends(QuadraticEase, _super);
  44838. function QuadraticEase() {
  44839. return _super !== null && _super.apply(this, arguments) || this;
  44840. }
  44841. QuadraticEase.prototype.easeInCore = function (gradient) {
  44842. return (gradient * gradient);
  44843. };
  44844. return QuadraticEase;
  44845. }(EasingFunction));
  44846. BABYLON.QuadraticEase = QuadraticEase;
  44847. var QuarticEase = /** @class */ (function (_super) {
  44848. __extends(QuarticEase, _super);
  44849. function QuarticEase() {
  44850. return _super !== null && _super.apply(this, arguments) || this;
  44851. }
  44852. QuarticEase.prototype.easeInCore = function (gradient) {
  44853. return (gradient * gradient * gradient * gradient);
  44854. };
  44855. return QuarticEase;
  44856. }(EasingFunction));
  44857. BABYLON.QuarticEase = QuarticEase;
  44858. var QuinticEase = /** @class */ (function (_super) {
  44859. __extends(QuinticEase, _super);
  44860. function QuinticEase() {
  44861. return _super !== null && _super.apply(this, arguments) || this;
  44862. }
  44863. QuinticEase.prototype.easeInCore = function (gradient) {
  44864. return (gradient * gradient * gradient * gradient * gradient);
  44865. };
  44866. return QuinticEase;
  44867. }(EasingFunction));
  44868. BABYLON.QuinticEase = QuinticEase;
  44869. var SineEase = /** @class */ (function (_super) {
  44870. __extends(SineEase, _super);
  44871. function SineEase() {
  44872. return _super !== null && _super.apply(this, arguments) || this;
  44873. }
  44874. SineEase.prototype.easeInCore = function (gradient) {
  44875. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  44876. };
  44877. return SineEase;
  44878. }(EasingFunction));
  44879. BABYLON.SineEase = SineEase;
  44880. var BezierCurveEase = /** @class */ (function (_super) {
  44881. __extends(BezierCurveEase, _super);
  44882. function BezierCurveEase(x1, y1, x2, y2) {
  44883. if (x1 === void 0) { x1 = 0; }
  44884. if (y1 === void 0) { y1 = 0; }
  44885. if (x2 === void 0) { x2 = 1; }
  44886. if (y2 === void 0) { y2 = 1; }
  44887. var _this = _super.call(this) || this;
  44888. _this.x1 = x1;
  44889. _this.y1 = y1;
  44890. _this.x2 = x2;
  44891. _this.y2 = y2;
  44892. return _this;
  44893. }
  44894. BezierCurveEase.prototype.easeInCore = function (gradient) {
  44895. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  44896. };
  44897. return BezierCurveEase;
  44898. }(EasingFunction));
  44899. BABYLON.BezierCurveEase = BezierCurveEase;
  44900. })(BABYLON || (BABYLON = {}));
  44901. //# sourceMappingURL=babylon.easing.js.map
  44902. var BABYLON;
  44903. (function (BABYLON) {
  44904. var Condition = /** @class */ (function () {
  44905. function Condition(actionManager) {
  44906. this._actionManager = actionManager;
  44907. }
  44908. Condition.prototype.isValid = function () {
  44909. return true;
  44910. };
  44911. Condition.prototype._getProperty = function (propertyPath) {
  44912. return this._actionManager._getProperty(propertyPath);
  44913. };
  44914. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  44915. return this._actionManager._getEffectiveTarget(target, propertyPath);
  44916. };
  44917. Condition.prototype.serialize = function () {
  44918. };
  44919. Condition.prototype._serialize = function (serializedCondition) {
  44920. return {
  44921. type: 2,
  44922. children: [],
  44923. name: serializedCondition.name,
  44924. properties: serializedCondition.properties
  44925. };
  44926. };
  44927. return Condition;
  44928. }());
  44929. BABYLON.Condition = Condition;
  44930. var ValueCondition = /** @class */ (function (_super) {
  44931. __extends(ValueCondition, _super);
  44932. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  44933. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  44934. var _this = _super.call(this, actionManager) || this;
  44935. _this.propertyPath = propertyPath;
  44936. _this.value = value;
  44937. _this.operator = operator;
  44938. _this._target = target;
  44939. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  44940. _this._property = _this._getProperty(_this.propertyPath);
  44941. return _this;
  44942. }
  44943. Object.defineProperty(ValueCondition, "IsEqual", {
  44944. get: function () {
  44945. return ValueCondition._IsEqual;
  44946. },
  44947. enumerable: true,
  44948. configurable: true
  44949. });
  44950. Object.defineProperty(ValueCondition, "IsDifferent", {
  44951. get: function () {
  44952. return ValueCondition._IsDifferent;
  44953. },
  44954. enumerable: true,
  44955. configurable: true
  44956. });
  44957. Object.defineProperty(ValueCondition, "IsGreater", {
  44958. get: function () {
  44959. return ValueCondition._IsGreater;
  44960. },
  44961. enumerable: true,
  44962. configurable: true
  44963. });
  44964. Object.defineProperty(ValueCondition, "IsLesser", {
  44965. get: function () {
  44966. return ValueCondition._IsLesser;
  44967. },
  44968. enumerable: true,
  44969. configurable: true
  44970. });
  44971. // Methods
  44972. ValueCondition.prototype.isValid = function () {
  44973. switch (this.operator) {
  44974. case ValueCondition.IsGreater:
  44975. return this._effectiveTarget[this._property] > this.value;
  44976. case ValueCondition.IsLesser:
  44977. return this._effectiveTarget[this._property] < this.value;
  44978. case ValueCondition.IsEqual:
  44979. case ValueCondition.IsDifferent:
  44980. var check;
  44981. if (this.value.equals) {
  44982. check = this.value.equals(this._effectiveTarget[this._property]);
  44983. }
  44984. else {
  44985. check = this.value === this._effectiveTarget[this._property];
  44986. }
  44987. return this.operator === ValueCondition.IsEqual ? check : !check;
  44988. }
  44989. return false;
  44990. };
  44991. ValueCondition.prototype.serialize = function () {
  44992. return this._serialize({
  44993. name: "ValueCondition",
  44994. properties: [
  44995. BABYLON.Action._GetTargetProperty(this._target),
  44996. { name: "propertyPath", value: this.propertyPath },
  44997. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  44998. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  44999. ]
  45000. });
  45001. };
  45002. ValueCondition.GetOperatorName = function (operator) {
  45003. switch (operator) {
  45004. case ValueCondition._IsEqual: return "IsEqual";
  45005. case ValueCondition._IsDifferent: return "IsDifferent";
  45006. case ValueCondition._IsGreater: return "IsGreater";
  45007. case ValueCondition._IsLesser: return "IsLesser";
  45008. default: return "";
  45009. }
  45010. };
  45011. // Statics
  45012. ValueCondition._IsEqual = 0;
  45013. ValueCondition._IsDifferent = 1;
  45014. ValueCondition._IsGreater = 2;
  45015. ValueCondition._IsLesser = 3;
  45016. return ValueCondition;
  45017. }(Condition));
  45018. BABYLON.ValueCondition = ValueCondition;
  45019. var PredicateCondition = /** @class */ (function (_super) {
  45020. __extends(PredicateCondition, _super);
  45021. function PredicateCondition(actionManager, predicate) {
  45022. var _this = _super.call(this, actionManager) || this;
  45023. _this.predicate = predicate;
  45024. return _this;
  45025. }
  45026. PredicateCondition.prototype.isValid = function () {
  45027. return this.predicate();
  45028. };
  45029. return PredicateCondition;
  45030. }(Condition));
  45031. BABYLON.PredicateCondition = PredicateCondition;
  45032. var StateCondition = /** @class */ (function (_super) {
  45033. __extends(StateCondition, _super);
  45034. function StateCondition(actionManager, target, value) {
  45035. var _this = _super.call(this, actionManager) || this;
  45036. _this.value = value;
  45037. _this._target = target;
  45038. return _this;
  45039. }
  45040. // Methods
  45041. StateCondition.prototype.isValid = function () {
  45042. return this._target.state === this.value;
  45043. };
  45044. StateCondition.prototype.serialize = function () {
  45045. return this._serialize({
  45046. name: "StateCondition",
  45047. properties: [
  45048. BABYLON.Action._GetTargetProperty(this._target),
  45049. { name: "value", value: this.value }
  45050. ]
  45051. });
  45052. };
  45053. return StateCondition;
  45054. }(Condition));
  45055. BABYLON.StateCondition = StateCondition;
  45056. })(BABYLON || (BABYLON = {}));
  45057. //# sourceMappingURL=babylon.condition.js.map
  45058. var BABYLON;
  45059. (function (BABYLON) {
  45060. var Action = /** @class */ (function () {
  45061. function Action(triggerOptions, condition) {
  45062. this.triggerOptions = triggerOptions;
  45063. this.onBeforeExecuteObservable = new BABYLON.Observable();
  45064. if (triggerOptions.parameter) {
  45065. this.trigger = triggerOptions.trigger;
  45066. this._triggerParameter = triggerOptions.parameter;
  45067. }
  45068. else {
  45069. this.trigger = triggerOptions;
  45070. }
  45071. this._nextActiveAction = this;
  45072. this._condition = condition;
  45073. }
  45074. // Methods
  45075. Action.prototype._prepare = function () {
  45076. };
  45077. Action.prototype.getTriggerParameter = function () {
  45078. return this._triggerParameter;
  45079. };
  45080. Action.prototype._executeCurrent = function (evt) {
  45081. if (this._nextActiveAction._condition) {
  45082. var condition = this._nextActiveAction._condition;
  45083. var currentRenderId = this._actionManager.getScene().getRenderId();
  45084. // We cache the current evaluation for the current frame
  45085. if (condition._evaluationId === currentRenderId) {
  45086. if (!condition._currentResult) {
  45087. return;
  45088. }
  45089. }
  45090. else {
  45091. condition._evaluationId = currentRenderId;
  45092. if (!condition.isValid()) {
  45093. condition._currentResult = false;
  45094. return;
  45095. }
  45096. condition._currentResult = true;
  45097. }
  45098. }
  45099. this.onBeforeExecuteObservable.notifyObservers(this);
  45100. this._nextActiveAction.execute(evt);
  45101. this.skipToNextActiveAction();
  45102. };
  45103. Action.prototype.execute = function (evt) {
  45104. };
  45105. Action.prototype.skipToNextActiveAction = function () {
  45106. if (this._nextActiveAction._child) {
  45107. if (!this._nextActiveAction._child._actionManager) {
  45108. this._nextActiveAction._child._actionManager = this._actionManager;
  45109. }
  45110. this._nextActiveAction = this._nextActiveAction._child;
  45111. }
  45112. else {
  45113. this._nextActiveAction = this;
  45114. }
  45115. };
  45116. Action.prototype.then = function (action) {
  45117. this._child = action;
  45118. action._actionManager = this._actionManager;
  45119. action._prepare();
  45120. return action;
  45121. };
  45122. Action.prototype._getProperty = function (propertyPath) {
  45123. return this._actionManager._getProperty(propertyPath);
  45124. };
  45125. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  45126. return this._actionManager._getEffectiveTarget(target, propertyPath);
  45127. };
  45128. Action.prototype.serialize = function (parent) {
  45129. };
  45130. // Called by BABYLON.Action objects in serialize(...). Internal use
  45131. Action.prototype._serialize = function (serializedAction, parent) {
  45132. var serializationObject = {
  45133. type: 1,
  45134. children: [],
  45135. name: serializedAction.name,
  45136. properties: serializedAction.properties || []
  45137. };
  45138. // Serialize child
  45139. if (this._child) {
  45140. this._child.serialize(serializationObject);
  45141. }
  45142. // Check if "this" has a condition
  45143. if (this._condition) {
  45144. var serializedCondition = this._condition.serialize();
  45145. serializedCondition.children.push(serializationObject);
  45146. if (parent) {
  45147. parent.children.push(serializedCondition);
  45148. }
  45149. return serializedCondition;
  45150. }
  45151. if (parent) {
  45152. parent.children.push(serializationObject);
  45153. }
  45154. return serializationObject;
  45155. };
  45156. Action._SerializeValueAsString = function (value) {
  45157. if (typeof value === "number") {
  45158. return value.toString();
  45159. }
  45160. if (typeof value === "boolean") {
  45161. return value ? "true" : "false";
  45162. }
  45163. if (value instanceof BABYLON.Vector2) {
  45164. return value.x + ", " + value.y;
  45165. }
  45166. if (value instanceof BABYLON.Vector3) {
  45167. return value.x + ", " + value.y + ", " + value.z;
  45168. }
  45169. if (value instanceof BABYLON.Color3) {
  45170. return value.r + ", " + value.g + ", " + value.b;
  45171. }
  45172. if (value instanceof BABYLON.Color4) {
  45173. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  45174. }
  45175. return value; // string
  45176. };
  45177. Action._GetTargetProperty = function (target) {
  45178. return {
  45179. name: "target",
  45180. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  45181. : target instanceof BABYLON.Light ? "LightProperties"
  45182. : target instanceof BABYLON.Camera ? "CameraProperties"
  45183. : "SceneProperties",
  45184. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  45185. };
  45186. };
  45187. return Action;
  45188. }());
  45189. BABYLON.Action = Action;
  45190. })(BABYLON || (BABYLON = {}));
  45191. //# sourceMappingURL=babylon.action.js.map
  45192. var BABYLON;
  45193. (function (BABYLON) {
  45194. /**
  45195. * ActionEvent is the event beint sent when an action is triggered.
  45196. */
  45197. var ActionEvent = /** @class */ (function () {
  45198. /**
  45199. * @param source The mesh or sprite that triggered the action.
  45200. * @param pointerX The X mouse cursor position at the time of the event
  45201. * @param pointerY The Y mouse cursor position at the time of the event
  45202. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  45203. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  45204. */
  45205. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  45206. this.source = source;
  45207. this.pointerX = pointerX;
  45208. this.pointerY = pointerY;
  45209. this.meshUnderPointer = meshUnderPointer;
  45210. this.sourceEvent = sourceEvent;
  45211. this.additionalData = additionalData;
  45212. }
  45213. /**
  45214. * Helper function to auto-create an ActionEvent from a source mesh.
  45215. * @param source The source mesh that triggered the event
  45216. * @param evt {Event} The original (browser) event
  45217. */
  45218. ActionEvent.CreateNew = function (source, evt, additionalData) {
  45219. var scene = source.getScene();
  45220. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  45221. };
  45222. /**
  45223. * Helper function to auto-create an ActionEvent from a source mesh.
  45224. * @param source The source sprite that triggered the event
  45225. * @param scene Scene associated with the sprite
  45226. * @param evt {Event} The original (browser) event
  45227. */
  45228. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  45229. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  45230. };
  45231. /**
  45232. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  45233. * @param scene the scene where the event occurred
  45234. * @param evt {Event} The original (browser) event
  45235. */
  45236. ActionEvent.CreateNewFromScene = function (scene, evt) {
  45237. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  45238. };
  45239. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  45240. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  45241. };
  45242. return ActionEvent;
  45243. }());
  45244. BABYLON.ActionEvent = ActionEvent;
  45245. /**
  45246. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  45247. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  45248. */
  45249. var ActionManager = /** @class */ (function () {
  45250. function ActionManager(scene) {
  45251. // Members
  45252. this.actions = new Array();
  45253. this.hoverCursor = '';
  45254. this._scene = scene;
  45255. scene._actionManagers.push(this);
  45256. }
  45257. Object.defineProperty(ActionManager, "NothingTrigger", {
  45258. get: function () {
  45259. return ActionManager._NothingTrigger;
  45260. },
  45261. enumerable: true,
  45262. configurable: true
  45263. });
  45264. Object.defineProperty(ActionManager, "OnPickTrigger", {
  45265. get: function () {
  45266. return ActionManager._OnPickTrigger;
  45267. },
  45268. enumerable: true,
  45269. configurable: true
  45270. });
  45271. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  45272. get: function () {
  45273. return ActionManager._OnLeftPickTrigger;
  45274. },
  45275. enumerable: true,
  45276. configurable: true
  45277. });
  45278. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  45279. get: function () {
  45280. return ActionManager._OnRightPickTrigger;
  45281. },
  45282. enumerable: true,
  45283. configurable: true
  45284. });
  45285. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  45286. get: function () {
  45287. return ActionManager._OnCenterPickTrigger;
  45288. },
  45289. enumerable: true,
  45290. configurable: true
  45291. });
  45292. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  45293. get: function () {
  45294. return ActionManager._OnPickDownTrigger;
  45295. },
  45296. enumerable: true,
  45297. configurable: true
  45298. });
  45299. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  45300. get: function () {
  45301. return ActionManager._OnDoublePickTrigger;
  45302. },
  45303. enumerable: true,
  45304. configurable: true
  45305. });
  45306. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  45307. get: function () {
  45308. return ActionManager._OnPickUpTrigger;
  45309. },
  45310. enumerable: true,
  45311. configurable: true
  45312. });
  45313. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  45314. /// This trigger will only be raised if you also declared a OnPickDown
  45315. get: function () {
  45316. return ActionManager._OnPickOutTrigger;
  45317. },
  45318. enumerable: true,
  45319. configurable: true
  45320. });
  45321. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  45322. get: function () {
  45323. return ActionManager._OnLongPressTrigger;
  45324. },
  45325. enumerable: true,
  45326. configurable: true
  45327. });
  45328. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  45329. get: function () {
  45330. return ActionManager._OnPointerOverTrigger;
  45331. },
  45332. enumerable: true,
  45333. configurable: true
  45334. });
  45335. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  45336. get: function () {
  45337. return ActionManager._OnPointerOutTrigger;
  45338. },
  45339. enumerable: true,
  45340. configurable: true
  45341. });
  45342. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  45343. get: function () {
  45344. return ActionManager._OnEveryFrameTrigger;
  45345. },
  45346. enumerable: true,
  45347. configurable: true
  45348. });
  45349. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  45350. get: function () {
  45351. return ActionManager._OnIntersectionEnterTrigger;
  45352. },
  45353. enumerable: true,
  45354. configurable: true
  45355. });
  45356. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  45357. get: function () {
  45358. return ActionManager._OnIntersectionExitTrigger;
  45359. },
  45360. enumerable: true,
  45361. configurable: true
  45362. });
  45363. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  45364. get: function () {
  45365. return ActionManager._OnKeyDownTrigger;
  45366. },
  45367. enumerable: true,
  45368. configurable: true
  45369. });
  45370. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  45371. get: function () {
  45372. return ActionManager._OnKeyUpTrigger;
  45373. },
  45374. enumerable: true,
  45375. configurable: true
  45376. });
  45377. // Methods
  45378. ActionManager.prototype.dispose = function () {
  45379. var index = this._scene._actionManagers.indexOf(this);
  45380. for (var i = 0; i < this.actions.length; i++) {
  45381. var action = this.actions[i];
  45382. ActionManager.Triggers[action.trigger]--;
  45383. if (ActionManager.Triggers[action.trigger] === 0) {
  45384. delete ActionManager.Triggers[action.trigger];
  45385. }
  45386. }
  45387. if (index > -1) {
  45388. this._scene._actionManagers.splice(index, 1);
  45389. }
  45390. };
  45391. ActionManager.prototype.getScene = function () {
  45392. return this._scene;
  45393. };
  45394. /**
  45395. * Does this action manager handles actions of any of the given triggers
  45396. * @param {number[]} triggers - the triggers to be tested
  45397. * @return {boolean} whether one (or more) of the triggers is handeled
  45398. */
  45399. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  45400. for (var index = 0; index < this.actions.length; index++) {
  45401. var action = this.actions[index];
  45402. if (triggers.indexOf(action.trigger) > -1) {
  45403. return true;
  45404. }
  45405. }
  45406. return false;
  45407. };
  45408. /**
  45409. * Does this action manager handles actions of a given trigger
  45410. * @param {number} trigger - the trigger to be tested
  45411. * @return {boolean} whether the trigger is handeled
  45412. */
  45413. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  45414. for (var index = 0; index < this.actions.length; index++) {
  45415. var action = this.actions[index];
  45416. if (action.trigger === trigger) {
  45417. return true;
  45418. }
  45419. }
  45420. return false;
  45421. };
  45422. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  45423. /**
  45424. * Does this action manager has pointer triggers
  45425. * @return {boolean} whether or not it has pointer triggers
  45426. */
  45427. get: function () {
  45428. for (var index = 0; index < this.actions.length; index++) {
  45429. var action = this.actions[index];
  45430. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  45431. return true;
  45432. }
  45433. }
  45434. return false;
  45435. },
  45436. enumerable: true,
  45437. configurable: true
  45438. });
  45439. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  45440. /**
  45441. * Does this action manager has pick triggers
  45442. * @return {boolean} whether or not it has pick triggers
  45443. */
  45444. get: function () {
  45445. for (var index = 0; index < this.actions.length; index++) {
  45446. var action = this.actions[index];
  45447. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  45448. return true;
  45449. }
  45450. }
  45451. return false;
  45452. },
  45453. enumerable: true,
  45454. configurable: true
  45455. });
  45456. Object.defineProperty(ActionManager, "HasTriggers", {
  45457. /**
  45458. * Does exist one action manager with at least one trigger
  45459. * @return {boolean} whether or not it exists one action manager with one trigger
  45460. **/
  45461. get: function () {
  45462. for (var t in ActionManager.Triggers) {
  45463. if (ActionManager.Triggers.hasOwnProperty(t)) {
  45464. return true;
  45465. }
  45466. }
  45467. return false;
  45468. },
  45469. enumerable: true,
  45470. configurable: true
  45471. });
  45472. Object.defineProperty(ActionManager, "HasPickTriggers", {
  45473. /**
  45474. * Does exist one action manager with at least one pick trigger
  45475. * @return {boolean} whether or not it exists one action manager with one pick trigger
  45476. **/
  45477. get: function () {
  45478. for (var t in ActionManager.Triggers) {
  45479. if (ActionManager.Triggers.hasOwnProperty(t)) {
  45480. var t_int = parseInt(t);
  45481. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  45482. return true;
  45483. }
  45484. }
  45485. }
  45486. return false;
  45487. },
  45488. enumerable: true,
  45489. configurable: true
  45490. });
  45491. /**
  45492. * Does exist one action manager that handles actions of a given trigger
  45493. * @param {number} trigger - the trigger to be tested
  45494. * @return {boolean} whether the trigger is handeled by at least one action manager
  45495. **/
  45496. ActionManager.HasSpecificTrigger = function (trigger) {
  45497. for (var t in ActionManager.Triggers) {
  45498. if (ActionManager.Triggers.hasOwnProperty(t)) {
  45499. var t_int = parseInt(t);
  45500. if (t_int === trigger) {
  45501. return true;
  45502. }
  45503. }
  45504. }
  45505. return false;
  45506. };
  45507. /**
  45508. * Registers an action to this action manager
  45509. * @param {BABYLON.Action} action - the action to be registered
  45510. * @return {BABYLON.Action} the action amended (prepared) after registration
  45511. */
  45512. ActionManager.prototype.registerAction = function (action) {
  45513. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  45514. if (this.getScene().actionManager !== this) {
  45515. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  45516. return null;
  45517. }
  45518. }
  45519. this.actions.push(action);
  45520. if (ActionManager.Triggers[action.trigger]) {
  45521. ActionManager.Triggers[action.trigger]++;
  45522. }
  45523. else {
  45524. ActionManager.Triggers[action.trigger] = 1;
  45525. }
  45526. action._actionManager = this;
  45527. action._prepare();
  45528. return action;
  45529. };
  45530. /**
  45531. * Unregisters an action to this action manager
  45532. * @param action The action to be unregistered
  45533. * @return whether the action has been unregistered
  45534. */
  45535. ActionManager.prototype.unregisterAction = function (action) {
  45536. var index = this.actions.indexOf(action);
  45537. if (index !== -1) {
  45538. this.actions.splice(index, 1);
  45539. ActionManager.Triggers[action.trigger] -= 1;
  45540. if (ActionManager.Triggers[action.trigger] === 0) {
  45541. delete ActionManager.Triggers[action.trigger];
  45542. }
  45543. delete action._actionManager;
  45544. return true;
  45545. }
  45546. return false;
  45547. };
  45548. /**
  45549. * Process a specific trigger
  45550. * @param {number} trigger - the trigger to process
  45551. * @param evt {BABYLON.ActionEvent} the event details to be processed
  45552. */
  45553. ActionManager.prototype.processTrigger = function (trigger, evt) {
  45554. for (var index = 0; index < this.actions.length; index++) {
  45555. var action = this.actions[index];
  45556. if (action.trigger === trigger) {
  45557. if (evt) {
  45558. if (trigger === ActionManager.OnKeyUpTrigger
  45559. || trigger === ActionManager.OnKeyDownTrigger) {
  45560. var parameter = action.getTriggerParameter();
  45561. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  45562. if (!parameter.toLowerCase) {
  45563. continue;
  45564. }
  45565. var lowerCase = parameter.toLowerCase();
  45566. if (lowerCase !== evt.sourceEvent.key) {
  45567. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  45568. var actualkey = String.fromCharCode(unicode).toLowerCase();
  45569. if (actualkey !== lowerCase) {
  45570. continue;
  45571. }
  45572. }
  45573. }
  45574. }
  45575. }
  45576. action._executeCurrent(evt);
  45577. }
  45578. }
  45579. };
  45580. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  45581. var properties = propertyPath.split(".");
  45582. for (var index = 0; index < properties.length - 1; index++) {
  45583. target = target[properties[index]];
  45584. }
  45585. return target;
  45586. };
  45587. ActionManager.prototype._getProperty = function (propertyPath) {
  45588. var properties = propertyPath.split(".");
  45589. return properties[properties.length - 1];
  45590. };
  45591. ActionManager.prototype.serialize = function (name) {
  45592. var root = {
  45593. children: new Array(),
  45594. name: name,
  45595. type: 3,
  45596. properties: new Array() // Empty for root but required
  45597. };
  45598. for (var i = 0; i < this.actions.length; i++) {
  45599. var triggerObject = {
  45600. type: 0,
  45601. children: new Array(),
  45602. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  45603. properties: new Array()
  45604. };
  45605. var triggerOptions = this.actions[i].triggerOptions;
  45606. if (triggerOptions && typeof triggerOptions !== "number") {
  45607. if (triggerOptions.parameter instanceof BABYLON.Node) {
  45608. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  45609. }
  45610. else {
  45611. var parameter = {};
  45612. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  45613. if (triggerOptions.parameter.mesh) {
  45614. parameter._meshId = triggerOptions.parameter.mesh.id;
  45615. }
  45616. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  45617. }
  45618. }
  45619. // Serialize child action, recursively
  45620. this.actions[i].serialize(triggerObject);
  45621. // Add serialized trigger
  45622. root.children.push(triggerObject);
  45623. }
  45624. return root;
  45625. };
  45626. ActionManager.Parse = function (parsedActions, object, scene) {
  45627. var actionManager = new ActionManager(scene);
  45628. if (object === null)
  45629. scene.actionManager = actionManager;
  45630. else
  45631. object.actionManager = actionManager;
  45632. // instanciate a new object
  45633. var instanciate = function (name, params) {
  45634. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  45635. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  45636. newInstance.constructor.apply(newInstance, params);
  45637. return newInstance;
  45638. };
  45639. var parseParameter = function (name, value, target, propertyPath) {
  45640. if (propertyPath === null) {
  45641. // String, boolean or float
  45642. var floatValue = parseFloat(value);
  45643. if (value === "true" || value === "false")
  45644. return value === "true";
  45645. else
  45646. return isNaN(floatValue) ? value : floatValue;
  45647. }
  45648. var effectiveTarget = propertyPath.split(".");
  45649. var values = value.split(",");
  45650. // Get effective Target
  45651. for (var i = 0; i < effectiveTarget.length; i++) {
  45652. target = target[effectiveTarget[i]];
  45653. }
  45654. // Return appropriate value with its type
  45655. if (typeof (target) === "boolean")
  45656. return values[0] === "true";
  45657. if (typeof (target) === "string")
  45658. return values[0];
  45659. // Parameters with multiple values such as Vector3 etc.
  45660. var split = new Array();
  45661. for (var i = 0; i < values.length; i++)
  45662. split.push(parseFloat(values[i]));
  45663. if (target instanceof BABYLON.Vector3)
  45664. return BABYLON.Vector3.FromArray(split);
  45665. if (target instanceof BABYLON.Vector4)
  45666. return BABYLON.Vector4.FromArray(split);
  45667. if (target instanceof BABYLON.Color3)
  45668. return BABYLON.Color3.FromArray(split);
  45669. if (target instanceof BABYLON.Color4)
  45670. return BABYLON.Color4.FromArray(split);
  45671. return parseFloat(values[0]);
  45672. };
  45673. // traverse graph per trigger
  45674. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  45675. if (combineArray === void 0) { combineArray = null; }
  45676. if (parsedAction.detached)
  45677. return;
  45678. var parameters = new Array();
  45679. var target = null;
  45680. var propertyPath = null;
  45681. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  45682. // Parameters
  45683. if (parsedAction.type === 2)
  45684. parameters.push(actionManager);
  45685. else
  45686. parameters.push(trigger);
  45687. if (combine) {
  45688. var actions = new Array();
  45689. for (var j = 0; j < parsedAction.combine.length; j++) {
  45690. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  45691. }
  45692. parameters.push(actions);
  45693. }
  45694. else {
  45695. for (var i = 0; i < parsedAction.properties.length; i++) {
  45696. var value = parsedAction.properties[i].value;
  45697. var name = parsedAction.properties[i].name;
  45698. var targetType = parsedAction.properties[i].targetType;
  45699. if (name === "target")
  45700. if (targetType !== null && targetType === "SceneProperties")
  45701. value = target = scene;
  45702. else
  45703. value = target = scene.getNodeByName(value);
  45704. else if (name === "parent")
  45705. value = scene.getNodeByName(value);
  45706. else if (name === "sound")
  45707. value = scene.getSoundByName(value);
  45708. else if (name !== "propertyPath") {
  45709. if (parsedAction.type === 2 && name === "operator")
  45710. value = BABYLON.ValueCondition[value];
  45711. else
  45712. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  45713. }
  45714. else {
  45715. propertyPath = value;
  45716. }
  45717. parameters.push(value);
  45718. }
  45719. }
  45720. if (combineArray === null) {
  45721. parameters.push(condition);
  45722. }
  45723. else {
  45724. parameters.push(null);
  45725. }
  45726. // If interpolate value action
  45727. if (parsedAction.name === "InterpolateValueAction") {
  45728. var param = parameters[parameters.length - 2];
  45729. parameters[parameters.length - 1] = param;
  45730. parameters[parameters.length - 2] = condition;
  45731. }
  45732. // Action or condition(s) and not CombineAction
  45733. var newAction = instanciate(parsedAction.name, parameters);
  45734. if (newAction instanceof BABYLON.Condition && condition !== null) {
  45735. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  45736. if (action)
  45737. action.then(nothing);
  45738. else
  45739. actionManager.registerAction(nothing);
  45740. action = nothing;
  45741. }
  45742. if (combineArray === null) {
  45743. if (newAction instanceof BABYLON.Condition) {
  45744. condition = newAction;
  45745. newAction = action;
  45746. }
  45747. else {
  45748. condition = null;
  45749. if (action)
  45750. action.then(newAction);
  45751. else
  45752. actionManager.registerAction(newAction);
  45753. }
  45754. }
  45755. else {
  45756. combineArray.push(newAction);
  45757. }
  45758. for (var i = 0; i < parsedAction.children.length; i++)
  45759. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  45760. };
  45761. // triggers
  45762. for (var i = 0; i < parsedActions.children.length; i++) {
  45763. var triggerParams;
  45764. var trigger = parsedActions.children[i];
  45765. if (trigger.properties.length > 0) {
  45766. var param = trigger.properties[0].value;
  45767. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  45768. if (value._meshId) {
  45769. value.mesh = scene.getMeshByID(value._meshId);
  45770. }
  45771. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  45772. }
  45773. else
  45774. triggerParams = ActionManager[trigger.name];
  45775. for (var j = 0; j < trigger.children.length; j++) {
  45776. if (!trigger.detached)
  45777. traverse(trigger.children[j], triggerParams, null, null);
  45778. }
  45779. }
  45780. };
  45781. ActionManager.GetTriggerName = function (trigger) {
  45782. switch (trigger) {
  45783. case 0: return "NothingTrigger";
  45784. case 1: return "OnPickTrigger";
  45785. case 2: return "OnLeftPickTrigger";
  45786. case 3: return "OnRightPickTrigger";
  45787. case 4: return "OnCenterPickTrigger";
  45788. case 5: return "OnPickDownTrigger";
  45789. case 6: return "OnPickUpTrigger";
  45790. case 7: return "OnLongPressTrigger";
  45791. case 8: return "OnPointerOverTrigger";
  45792. case 9: return "OnPointerOutTrigger";
  45793. case 10: return "OnEveryFrameTrigger";
  45794. case 11: return "OnIntersectionEnterTrigger";
  45795. case 12: return "OnIntersectionExitTrigger";
  45796. case 13: return "OnKeyDownTrigger";
  45797. case 14: return "OnKeyUpTrigger";
  45798. case 15: return "OnPickOutTrigger";
  45799. default: return "";
  45800. }
  45801. };
  45802. // Statics
  45803. ActionManager._NothingTrigger = 0;
  45804. ActionManager._OnPickTrigger = 1;
  45805. ActionManager._OnLeftPickTrigger = 2;
  45806. ActionManager._OnRightPickTrigger = 3;
  45807. ActionManager._OnCenterPickTrigger = 4;
  45808. ActionManager._OnPickDownTrigger = 5;
  45809. ActionManager._OnDoublePickTrigger = 6;
  45810. ActionManager._OnPickUpTrigger = 7;
  45811. ActionManager._OnLongPressTrigger = 8;
  45812. ActionManager._OnPointerOverTrigger = 9;
  45813. ActionManager._OnPointerOutTrigger = 10;
  45814. ActionManager._OnEveryFrameTrigger = 11;
  45815. ActionManager._OnIntersectionEnterTrigger = 12;
  45816. ActionManager._OnIntersectionExitTrigger = 13;
  45817. ActionManager._OnKeyDownTrigger = 14;
  45818. ActionManager._OnKeyUpTrigger = 15;
  45819. ActionManager._OnPickOutTrigger = 16;
  45820. ActionManager.Triggers = {};
  45821. return ActionManager;
  45822. }());
  45823. BABYLON.ActionManager = ActionManager;
  45824. })(BABYLON || (BABYLON = {}));
  45825. //# sourceMappingURL=babylon.actionManager.js.map
  45826. var BABYLON;
  45827. (function (BABYLON) {
  45828. var InterpolateValueAction = /** @class */ (function (_super) {
  45829. __extends(InterpolateValueAction, _super);
  45830. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  45831. if (duration === void 0) { duration = 1000; }
  45832. var _this = _super.call(this, triggerOptions, condition) || this;
  45833. _this.propertyPath = propertyPath;
  45834. _this.value = value;
  45835. _this.duration = duration;
  45836. _this.stopOtherAnimations = stopOtherAnimations;
  45837. _this.onInterpolationDone = onInterpolationDone;
  45838. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  45839. _this._target = _this._effectiveTarget = target;
  45840. return _this;
  45841. }
  45842. InterpolateValueAction.prototype._prepare = function () {
  45843. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  45844. this._property = this._getProperty(this.propertyPath);
  45845. };
  45846. InterpolateValueAction.prototype.execute = function () {
  45847. var _this = this;
  45848. var scene = this._actionManager.getScene();
  45849. var keys = [
  45850. {
  45851. frame: 0,
  45852. value: this._effectiveTarget[this._property]
  45853. }, {
  45854. frame: 100,
  45855. value: this.value
  45856. }
  45857. ];
  45858. var dataType;
  45859. if (typeof this.value === "number") {
  45860. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  45861. }
  45862. else if (this.value instanceof BABYLON.Color3) {
  45863. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  45864. }
  45865. else if (this.value instanceof BABYLON.Vector3) {
  45866. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  45867. }
  45868. else if (this.value instanceof BABYLON.Matrix) {
  45869. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  45870. }
  45871. else if (this.value instanceof BABYLON.Quaternion) {
  45872. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  45873. }
  45874. else {
  45875. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  45876. return;
  45877. }
  45878. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  45879. animation.setKeys(keys);
  45880. if (this.stopOtherAnimations) {
  45881. scene.stopAnimation(this._effectiveTarget);
  45882. }
  45883. var wrapper = function () {
  45884. _this.onInterpolationDoneObservable.notifyObservers(_this);
  45885. if (_this.onInterpolationDone) {
  45886. _this.onInterpolationDone();
  45887. }
  45888. };
  45889. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  45890. };
  45891. InterpolateValueAction.prototype.serialize = function (parent) {
  45892. return _super.prototype._serialize.call(this, {
  45893. name: "InterpolateValueAction",
  45894. properties: [
  45895. BABYLON.Action._GetTargetProperty(this._target),
  45896. { name: "propertyPath", value: this.propertyPath },
  45897. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  45898. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  45899. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  45900. ]
  45901. }, parent);
  45902. };
  45903. return InterpolateValueAction;
  45904. }(BABYLON.Action));
  45905. BABYLON.InterpolateValueAction = InterpolateValueAction;
  45906. })(BABYLON || (BABYLON = {}));
  45907. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  45908. var BABYLON;
  45909. (function (BABYLON) {
  45910. var SwitchBooleanAction = /** @class */ (function (_super) {
  45911. __extends(SwitchBooleanAction, _super);
  45912. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  45913. var _this = _super.call(this, triggerOptions, condition) || this;
  45914. _this.propertyPath = propertyPath;
  45915. _this._target = _this._effectiveTarget = target;
  45916. return _this;
  45917. }
  45918. SwitchBooleanAction.prototype._prepare = function () {
  45919. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  45920. this._property = this._getProperty(this.propertyPath);
  45921. };
  45922. SwitchBooleanAction.prototype.execute = function () {
  45923. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  45924. };
  45925. SwitchBooleanAction.prototype.serialize = function (parent) {
  45926. return _super.prototype._serialize.call(this, {
  45927. name: "SwitchBooleanAction",
  45928. properties: [
  45929. BABYLON.Action._GetTargetProperty(this._target),
  45930. { name: "propertyPath", value: this.propertyPath }
  45931. ]
  45932. }, parent);
  45933. };
  45934. return SwitchBooleanAction;
  45935. }(BABYLON.Action));
  45936. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  45937. var SetStateAction = /** @class */ (function (_super) {
  45938. __extends(SetStateAction, _super);
  45939. function SetStateAction(triggerOptions, target, value, condition) {
  45940. var _this = _super.call(this, triggerOptions, condition) || this;
  45941. _this.value = value;
  45942. _this._target = target;
  45943. return _this;
  45944. }
  45945. SetStateAction.prototype.execute = function () {
  45946. this._target.state = this.value;
  45947. };
  45948. SetStateAction.prototype.serialize = function (parent) {
  45949. return _super.prototype._serialize.call(this, {
  45950. name: "SetStateAction",
  45951. properties: [
  45952. BABYLON.Action._GetTargetProperty(this._target),
  45953. { name: "value", value: this.value }
  45954. ]
  45955. }, parent);
  45956. };
  45957. return SetStateAction;
  45958. }(BABYLON.Action));
  45959. BABYLON.SetStateAction = SetStateAction;
  45960. var SetValueAction = /** @class */ (function (_super) {
  45961. __extends(SetValueAction, _super);
  45962. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  45963. var _this = _super.call(this, triggerOptions, condition) || this;
  45964. _this.propertyPath = propertyPath;
  45965. _this.value = value;
  45966. _this._target = _this._effectiveTarget = target;
  45967. return _this;
  45968. }
  45969. SetValueAction.prototype._prepare = function () {
  45970. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  45971. this._property = this._getProperty(this.propertyPath);
  45972. };
  45973. SetValueAction.prototype.execute = function () {
  45974. this._effectiveTarget[this._property] = this.value;
  45975. if (this._target.markAsDirty) {
  45976. this._target.markAsDirty(this._property);
  45977. }
  45978. };
  45979. SetValueAction.prototype.serialize = function (parent) {
  45980. return _super.prototype._serialize.call(this, {
  45981. name: "SetValueAction",
  45982. properties: [
  45983. BABYLON.Action._GetTargetProperty(this._target),
  45984. { name: "propertyPath", value: this.propertyPath },
  45985. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  45986. ]
  45987. }, parent);
  45988. };
  45989. return SetValueAction;
  45990. }(BABYLON.Action));
  45991. BABYLON.SetValueAction = SetValueAction;
  45992. var IncrementValueAction = /** @class */ (function (_super) {
  45993. __extends(IncrementValueAction, _super);
  45994. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  45995. var _this = _super.call(this, triggerOptions, condition) || this;
  45996. _this.propertyPath = propertyPath;
  45997. _this.value = value;
  45998. _this._target = _this._effectiveTarget = target;
  45999. return _this;
  46000. }
  46001. IncrementValueAction.prototype._prepare = function () {
  46002. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  46003. this._property = this._getProperty(this.propertyPath);
  46004. if (typeof this._effectiveTarget[this._property] !== "number") {
  46005. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  46006. }
  46007. };
  46008. IncrementValueAction.prototype.execute = function () {
  46009. this._effectiveTarget[this._property] += this.value;
  46010. if (this._target.markAsDirty) {
  46011. this._target.markAsDirty(this._property);
  46012. }
  46013. };
  46014. IncrementValueAction.prototype.serialize = function (parent) {
  46015. return _super.prototype._serialize.call(this, {
  46016. name: "IncrementValueAction",
  46017. properties: [
  46018. BABYLON.Action._GetTargetProperty(this._target),
  46019. { name: "propertyPath", value: this.propertyPath },
  46020. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  46021. ]
  46022. }, parent);
  46023. };
  46024. return IncrementValueAction;
  46025. }(BABYLON.Action));
  46026. BABYLON.IncrementValueAction = IncrementValueAction;
  46027. var PlayAnimationAction = /** @class */ (function (_super) {
  46028. __extends(PlayAnimationAction, _super);
  46029. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  46030. var _this = _super.call(this, triggerOptions, condition) || this;
  46031. _this.from = from;
  46032. _this.to = to;
  46033. _this.loop = loop;
  46034. _this._target = target;
  46035. return _this;
  46036. }
  46037. PlayAnimationAction.prototype._prepare = function () {
  46038. };
  46039. PlayAnimationAction.prototype.execute = function () {
  46040. var scene = this._actionManager.getScene();
  46041. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  46042. };
  46043. PlayAnimationAction.prototype.serialize = function (parent) {
  46044. return _super.prototype._serialize.call(this, {
  46045. name: "PlayAnimationAction",
  46046. properties: [
  46047. BABYLON.Action._GetTargetProperty(this._target),
  46048. { name: "from", value: String(this.from) },
  46049. { name: "to", value: String(this.to) },
  46050. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  46051. ]
  46052. }, parent);
  46053. };
  46054. return PlayAnimationAction;
  46055. }(BABYLON.Action));
  46056. BABYLON.PlayAnimationAction = PlayAnimationAction;
  46057. var StopAnimationAction = /** @class */ (function (_super) {
  46058. __extends(StopAnimationAction, _super);
  46059. function StopAnimationAction(triggerOptions, target, condition) {
  46060. var _this = _super.call(this, triggerOptions, condition) || this;
  46061. _this._target = target;
  46062. return _this;
  46063. }
  46064. StopAnimationAction.prototype._prepare = function () {
  46065. };
  46066. StopAnimationAction.prototype.execute = function () {
  46067. var scene = this._actionManager.getScene();
  46068. scene.stopAnimation(this._target);
  46069. };
  46070. StopAnimationAction.prototype.serialize = function (parent) {
  46071. return _super.prototype._serialize.call(this, {
  46072. name: "StopAnimationAction",
  46073. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  46074. }, parent);
  46075. };
  46076. return StopAnimationAction;
  46077. }(BABYLON.Action));
  46078. BABYLON.StopAnimationAction = StopAnimationAction;
  46079. var DoNothingAction = /** @class */ (function (_super) {
  46080. __extends(DoNothingAction, _super);
  46081. function DoNothingAction(triggerOptions, condition) {
  46082. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  46083. return _super.call(this, triggerOptions, condition) || this;
  46084. }
  46085. DoNothingAction.prototype.execute = function () {
  46086. };
  46087. DoNothingAction.prototype.serialize = function (parent) {
  46088. return _super.prototype._serialize.call(this, {
  46089. name: "DoNothingAction",
  46090. properties: []
  46091. }, parent);
  46092. };
  46093. return DoNothingAction;
  46094. }(BABYLON.Action));
  46095. BABYLON.DoNothingAction = DoNothingAction;
  46096. var CombineAction = /** @class */ (function (_super) {
  46097. __extends(CombineAction, _super);
  46098. function CombineAction(triggerOptions, children, condition) {
  46099. var _this = _super.call(this, triggerOptions, condition) || this;
  46100. _this.children = children;
  46101. return _this;
  46102. }
  46103. CombineAction.prototype._prepare = function () {
  46104. for (var index = 0; index < this.children.length; index++) {
  46105. this.children[index]._actionManager = this._actionManager;
  46106. this.children[index]._prepare();
  46107. }
  46108. };
  46109. CombineAction.prototype.execute = function (evt) {
  46110. for (var index = 0; index < this.children.length; index++) {
  46111. this.children[index].execute(evt);
  46112. }
  46113. };
  46114. CombineAction.prototype.serialize = function (parent) {
  46115. var serializationObject = _super.prototype._serialize.call(this, {
  46116. name: "CombineAction",
  46117. properties: [],
  46118. combine: []
  46119. }, parent);
  46120. for (var i = 0; i < this.children.length; i++) {
  46121. serializationObject.combine.push(this.children[i].serialize(null));
  46122. }
  46123. return serializationObject;
  46124. };
  46125. return CombineAction;
  46126. }(BABYLON.Action));
  46127. BABYLON.CombineAction = CombineAction;
  46128. var ExecuteCodeAction = /** @class */ (function (_super) {
  46129. __extends(ExecuteCodeAction, _super);
  46130. function ExecuteCodeAction(triggerOptions, func, condition) {
  46131. var _this = _super.call(this, triggerOptions, condition) || this;
  46132. _this.func = func;
  46133. return _this;
  46134. }
  46135. ExecuteCodeAction.prototype.execute = function (evt) {
  46136. this.func(evt);
  46137. };
  46138. return ExecuteCodeAction;
  46139. }(BABYLON.Action));
  46140. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  46141. var SetParentAction = /** @class */ (function (_super) {
  46142. __extends(SetParentAction, _super);
  46143. function SetParentAction(triggerOptions, target, parent, condition) {
  46144. var _this = _super.call(this, triggerOptions, condition) || this;
  46145. _this._target = target;
  46146. _this._parent = parent;
  46147. return _this;
  46148. }
  46149. SetParentAction.prototype._prepare = function () {
  46150. };
  46151. SetParentAction.prototype.execute = function () {
  46152. if (this._target.parent === this._parent) {
  46153. return;
  46154. }
  46155. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  46156. invertParentWorldMatrix.invert();
  46157. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  46158. this._target.parent = this._parent;
  46159. };
  46160. SetParentAction.prototype.serialize = function (parent) {
  46161. return _super.prototype._serialize.call(this, {
  46162. name: "SetParentAction",
  46163. properties: [
  46164. BABYLON.Action._GetTargetProperty(this._target),
  46165. BABYLON.Action._GetTargetProperty(this._parent),
  46166. ]
  46167. }, parent);
  46168. };
  46169. return SetParentAction;
  46170. }(BABYLON.Action));
  46171. BABYLON.SetParentAction = SetParentAction;
  46172. var PlaySoundAction = /** @class */ (function (_super) {
  46173. __extends(PlaySoundAction, _super);
  46174. function PlaySoundAction(triggerOptions, sound, condition) {
  46175. var _this = _super.call(this, triggerOptions, condition) || this;
  46176. _this._sound = sound;
  46177. return _this;
  46178. }
  46179. PlaySoundAction.prototype._prepare = function () {
  46180. };
  46181. PlaySoundAction.prototype.execute = function () {
  46182. if (this._sound !== undefined)
  46183. this._sound.play();
  46184. };
  46185. PlaySoundAction.prototype.serialize = function (parent) {
  46186. return _super.prototype._serialize.call(this, {
  46187. name: "PlaySoundAction",
  46188. properties: [{ name: "sound", value: this._sound.name }]
  46189. }, parent);
  46190. };
  46191. return PlaySoundAction;
  46192. }(BABYLON.Action));
  46193. BABYLON.PlaySoundAction = PlaySoundAction;
  46194. var StopSoundAction = /** @class */ (function (_super) {
  46195. __extends(StopSoundAction, _super);
  46196. function StopSoundAction(triggerOptions, sound, condition) {
  46197. var _this = _super.call(this, triggerOptions, condition) || this;
  46198. _this._sound = sound;
  46199. return _this;
  46200. }
  46201. StopSoundAction.prototype._prepare = function () {
  46202. };
  46203. StopSoundAction.prototype.execute = function () {
  46204. if (this._sound !== undefined)
  46205. this._sound.stop();
  46206. };
  46207. StopSoundAction.prototype.serialize = function (parent) {
  46208. return _super.prototype._serialize.call(this, {
  46209. name: "StopSoundAction",
  46210. properties: [{ name: "sound", value: this._sound.name }]
  46211. }, parent);
  46212. };
  46213. return StopSoundAction;
  46214. }(BABYLON.Action));
  46215. BABYLON.StopSoundAction = StopSoundAction;
  46216. })(BABYLON || (BABYLON = {}));
  46217. //# sourceMappingURL=babylon.directActions.js.map
  46218. var BABYLON;
  46219. (function (BABYLON) {
  46220. var SpriteManager = /** @class */ (function () {
  46221. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  46222. if (epsilon === void 0) { epsilon = 0.01; }
  46223. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46224. this.name = name;
  46225. this.sprites = new Array();
  46226. this.renderingGroupId = 0;
  46227. this.layerMask = 0x0FFFFFFF;
  46228. this.fogEnabled = true;
  46229. this.isPickable = false;
  46230. /**
  46231. * An event triggered when the manager is disposed.
  46232. * @type {BABYLON.Observable}
  46233. */
  46234. this.onDisposeObservable = new BABYLON.Observable();
  46235. this._vertexBuffers = {};
  46236. this._capacity = capacity;
  46237. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  46238. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46239. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46240. if (cellSize.width && cellSize.height) {
  46241. this.cellWidth = cellSize.width;
  46242. this.cellHeight = cellSize.height;
  46243. }
  46244. else if (cellSize !== undefined) {
  46245. this.cellWidth = cellSize;
  46246. this.cellHeight = cellSize;
  46247. }
  46248. else {
  46249. return;
  46250. }
  46251. this._epsilon = epsilon;
  46252. this._scene = scene;
  46253. this._scene.spriteManagers.push(this);
  46254. var indices = [];
  46255. var index = 0;
  46256. for (var count = 0; count < capacity; count++) {
  46257. indices.push(index);
  46258. indices.push(index + 1);
  46259. indices.push(index + 2);
  46260. indices.push(index);
  46261. indices.push(index + 2);
  46262. indices.push(index + 3);
  46263. index += 4;
  46264. }
  46265. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  46266. // VBO
  46267. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  46268. this._vertexData = new Float32Array(capacity * 16 * 4);
  46269. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  46270. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  46271. var options = this._buffer.createVertexBuffer("options", 4, 4);
  46272. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  46273. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  46274. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  46275. this._vertexBuffers["options"] = options;
  46276. this._vertexBuffers["cellInfo"] = cellInfo;
  46277. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  46278. // Effects
  46279. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  46280. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  46281. }
  46282. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  46283. set: function (callback) {
  46284. if (this._onDisposeObserver) {
  46285. this.onDisposeObservable.remove(this._onDisposeObserver);
  46286. }
  46287. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  46288. },
  46289. enumerable: true,
  46290. configurable: true
  46291. });
  46292. Object.defineProperty(SpriteManager.prototype, "texture", {
  46293. get: function () {
  46294. return this._spriteTexture;
  46295. },
  46296. set: function (value) {
  46297. this._spriteTexture = value;
  46298. },
  46299. enumerable: true,
  46300. configurable: true
  46301. });
  46302. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  46303. var arrayOffset = index * 16;
  46304. if (offsetX === 0)
  46305. offsetX = this._epsilon;
  46306. else if (offsetX === 1)
  46307. offsetX = 1 - this._epsilon;
  46308. if (offsetY === 0)
  46309. offsetY = this._epsilon;
  46310. else if (offsetY === 1)
  46311. offsetY = 1 - this._epsilon;
  46312. this._vertexData[arrayOffset] = sprite.position.x;
  46313. this._vertexData[arrayOffset + 1] = sprite.position.y;
  46314. this._vertexData[arrayOffset + 2] = sprite.position.z;
  46315. this._vertexData[arrayOffset + 3] = sprite.angle;
  46316. this._vertexData[arrayOffset + 4] = sprite.width;
  46317. this._vertexData[arrayOffset + 5] = sprite.height;
  46318. this._vertexData[arrayOffset + 6] = offsetX;
  46319. this._vertexData[arrayOffset + 7] = offsetY;
  46320. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  46321. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  46322. var offset = (sprite.cellIndex / rowSize) >> 0;
  46323. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  46324. this._vertexData[arrayOffset + 11] = offset;
  46325. // Color
  46326. this._vertexData[arrayOffset + 12] = sprite.color.r;
  46327. this._vertexData[arrayOffset + 13] = sprite.color.g;
  46328. this._vertexData[arrayOffset + 14] = sprite.color.b;
  46329. this._vertexData[arrayOffset + 15] = sprite.color.a;
  46330. };
  46331. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  46332. var count = Math.min(this._capacity, this.sprites.length);
  46333. var min = BABYLON.Vector3.Zero();
  46334. var max = BABYLON.Vector3.Zero();
  46335. var distance = Number.MAX_VALUE;
  46336. var currentSprite = null;
  46337. var cameraSpacePosition = BABYLON.Vector3.Zero();
  46338. var cameraView = camera.getViewMatrix();
  46339. for (var index = 0; index < count; index++) {
  46340. var sprite = this.sprites[index];
  46341. if (!sprite) {
  46342. continue;
  46343. }
  46344. if (predicate) {
  46345. if (!predicate(sprite)) {
  46346. continue;
  46347. }
  46348. }
  46349. else if (!sprite.isPickable) {
  46350. continue;
  46351. }
  46352. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  46353. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  46354. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  46355. if (ray.intersectsBoxMinMax(min, max)) {
  46356. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  46357. if (distance > currentDistance) {
  46358. distance = currentDistance;
  46359. currentSprite = sprite;
  46360. if (fastCheck) {
  46361. break;
  46362. }
  46363. }
  46364. }
  46365. }
  46366. if (currentSprite) {
  46367. var result = new BABYLON.PickingInfo();
  46368. result.hit = true;
  46369. result.pickedSprite = currentSprite;
  46370. result.distance = distance;
  46371. return result;
  46372. }
  46373. return null;
  46374. };
  46375. SpriteManager.prototype.render = function () {
  46376. // Check
  46377. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  46378. return;
  46379. var engine = this._scene.getEngine();
  46380. var baseSize = this._spriteTexture.getBaseSize();
  46381. // Sprites
  46382. var deltaTime = engine.getDeltaTime();
  46383. var max = Math.min(this._capacity, this.sprites.length);
  46384. var rowSize = baseSize.width / this.cellWidth;
  46385. var offset = 0;
  46386. for (var index = 0; index < max; index++) {
  46387. var sprite = this.sprites[index];
  46388. if (!sprite) {
  46389. continue;
  46390. }
  46391. sprite._animate(deltaTime);
  46392. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  46393. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  46394. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  46395. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  46396. }
  46397. this._buffer.update(this._vertexData);
  46398. // Render
  46399. var effect = this._effectBase;
  46400. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  46401. effect = this._effectFog;
  46402. }
  46403. engine.enableEffect(effect);
  46404. var viewMatrix = this._scene.getViewMatrix();
  46405. effect.setTexture("diffuseSampler", this._spriteTexture);
  46406. effect.setMatrix("view", viewMatrix);
  46407. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  46408. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  46409. // Fog
  46410. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  46411. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  46412. effect.setColor3("vFogColor", this._scene.fogColor);
  46413. }
  46414. // VBOs
  46415. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  46416. // Draw order
  46417. engine.setDepthFunctionToLessOrEqual();
  46418. effect.setBool("alphaTest", true);
  46419. engine.setColorWrite(false);
  46420. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  46421. engine.setColorWrite(true);
  46422. effect.setBool("alphaTest", false);
  46423. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  46424. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  46425. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  46426. };
  46427. SpriteManager.prototype.dispose = function () {
  46428. if (this._buffer) {
  46429. this._buffer.dispose();
  46430. this._buffer = null;
  46431. }
  46432. if (this._indexBuffer) {
  46433. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  46434. this._indexBuffer = null;
  46435. }
  46436. if (this._spriteTexture) {
  46437. this._spriteTexture.dispose();
  46438. this._spriteTexture = null;
  46439. }
  46440. // Remove from scene
  46441. var index = this._scene.spriteManagers.indexOf(this);
  46442. this._scene.spriteManagers.splice(index, 1);
  46443. // Callback
  46444. this.onDisposeObservable.notifyObservers(this);
  46445. this.onDisposeObservable.clear();
  46446. };
  46447. return SpriteManager;
  46448. }());
  46449. BABYLON.SpriteManager = SpriteManager;
  46450. })(BABYLON || (BABYLON = {}));
  46451. //# sourceMappingURL=babylon.spriteManager.js.map
  46452. var BABYLON;
  46453. (function (BABYLON) {
  46454. var Sprite = /** @class */ (function () {
  46455. function Sprite(name, manager) {
  46456. this.name = name;
  46457. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  46458. this.width = 1.0;
  46459. this.height = 1.0;
  46460. this.angle = 0;
  46461. this.cellIndex = 0;
  46462. this.invertU = 0;
  46463. this.invertV = 0;
  46464. this.animations = new Array();
  46465. this.isPickable = false;
  46466. this._animationStarted = false;
  46467. this._loopAnimation = false;
  46468. this._fromIndex = 0;
  46469. this._toIndex = 0;
  46470. this._delay = 0;
  46471. this._direction = 1;
  46472. this._time = 0;
  46473. this._manager = manager;
  46474. this._manager.sprites.push(this);
  46475. this.position = BABYLON.Vector3.Zero();
  46476. }
  46477. Object.defineProperty(Sprite.prototype, "size", {
  46478. get: function () {
  46479. return this.width;
  46480. },
  46481. set: function (value) {
  46482. this.width = value;
  46483. this.height = value;
  46484. },
  46485. enumerable: true,
  46486. configurable: true
  46487. });
  46488. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  46489. this._fromIndex = from;
  46490. this._toIndex = to;
  46491. this._loopAnimation = loop;
  46492. this._delay = delay;
  46493. this._animationStarted = true;
  46494. this._direction = from < to ? 1 : -1;
  46495. this.cellIndex = from;
  46496. this._time = 0;
  46497. this._onAnimationEnd = onAnimationEnd;
  46498. };
  46499. Sprite.prototype.stopAnimation = function () {
  46500. this._animationStarted = false;
  46501. };
  46502. Sprite.prototype._animate = function (deltaTime) {
  46503. if (!this._animationStarted)
  46504. return;
  46505. this._time += deltaTime;
  46506. if (this._time > this._delay) {
  46507. this._time = this._time % this._delay;
  46508. this.cellIndex += this._direction;
  46509. if (this.cellIndex > this._toIndex) {
  46510. if (this._loopAnimation) {
  46511. this.cellIndex = this._fromIndex;
  46512. }
  46513. else {
  46514. this.cellIndex = this._toIndex;
  46515. this._animationStarted = false;
  46516. if (this._onAnimationEnd) {
  46517. this._onAnimationEnd();
  46518. }
  46519. if (this.disposeWhenFinishedAnimating) {
  46520. this.dispose();
  46521. }
  46522. }
  46523. }
  46524. }
  46525. };
  46526. Sprite.prototype.dispose = function () {
  46527. for (var i = 0; i < this._manager.sprites.length; i++) {
  46528. if (this._manager.sprites[i] == this) {
  46529. this._manager.sprites.splice(i, 1);
  46530. }
  46531. }
  46532. };
  46533. return Sprite;
  46534. }());
  46535. BABYLON.Sprite = Sprite;
  46536. })(BABYLON || (BABYLON = {}));
  46537. //# sourceMappingURL=babylon.sprite.js.map
  46538. var BABYLON;
  46539. (function (BABYLON) {
  46540. var IntersectionInfo = /** @class */ (function () {
  46541. function IntersectionInfo(bu, bv, distance) {
  46542. this.bu = bu;
  46543. this.bv = bv;
  46544. this.distance = distance;
  46545. this.faceId = 0;
  46546. this.subMeshId = 0;
  46547. }
  46548. return IntersectionInfo;
  46549. }());
  46550. BABYLON.IntersectionInfo = IntersectionInfo;
  46551. var PickingInfo = /** @class */ (function () {
  46552. function PickingInfo() {
  46553. this.hit = false;
  46554. this.distance = 0;
  46555. this.pickedPoint = null;
  46556. this.pickedMesh = null;
  46557. this.bu = 0;
  46558. this.bv = 0;
  46559. this.faceId = -1;
  46560. this.subMeshId = 0;
  46561. this.pickedSprite = null;
  46562. }
  46563. // Methods
  46564. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  46565. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  46566. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  46567. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  46568. return null;
  46569. }
  46570. var indices = this.pickedMesh.getIndices();
  46571. if (!indices) {
  46572. return null;
  46573. }
  46574. var result;
  46575. if (useVerticesNormals) {
  46576. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  46577. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  46578. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  46579. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  46580. normal0 = normal0.scale(this.bu);
  46581. normal1 = normal1.scale(this.bv);
  46582. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  46583. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  46584. }
  46585. else {
  46586. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  46587. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  46588. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  46589. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  46590. var p1p2 = vertex1.subtract(vertex2);
  46591. var p3p2 = vertex3.subtract(vertex2);
  46592. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  46593. }
  46594. if (useWorldCoordinates) {
  46595. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  46596. }
  46597. return BABYLON.Vector3.Normalize(result);
  46598. };
  46599. PickingInfo.prototype.getTextureCoordinates = function () {
  46600. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  46601. return null;
  46602. }
  46603. var indices = this.pickedMesh.getIndices();
  46604. if (!indices) {
  46605. return null;
  46606. }
  46607. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  46608. if (!uvs) {
  46609. return null;
  46610. }
  46611. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  46612. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  46613. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  46614. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  46615. uv1 = uv1.scale(this.bu);
  46616. uv2 = uv2.scale(this.bv);
  46617. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  46618. };
  46619. return PickingInfo;
  46620. }());
  46621. BABYLON.PickingInfo = PickingInfo;
  46622. })(BABYLON || (BABYLON = {}));
  46623. //# sourceMappingURL=babylon.pickingInfo.js.map
  46624. var BABYLON;
  46625. (function (BABYLON) {
  46626. var Ray = /** @class */ (function () {
  46627. function Ray(origin, direction, length) {
  46628. if (length === void 0) { length = Number.MAX_VALUE; }
  46629. this.origin = origin;
  46630. this.direction = direction;
  46631. this.length = length;
  46632. }
  46633. // Methods
  46634. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  46635. var d = 0.0;
  46636. var maxValue = Number.MAX_VALUE;
  46637. var inv;
  46638. var min;
  46639. var max;
  46640. var temp;
  46641. if (Math.abs(this.direction.x) < 0.0000001) {
  46642. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  46643. return false;
  46644. }
  46645. }
  46646. else {
  46647. inv = 1.0 / this.direction.x;
  46648. min = (minimum.x - this.origin.x) * inv;
  46649. max = (maximum.x - this.origin.x) * inv;
  46650. if (max === -Infinity) {
  46651. max = Infinity;
  46652. }
  46653. if (min > max) {
  46654. temp = min;
  46655. min = max;
  46656. max = temp;
  46657. }
  46658. d = Math.max(min, d);
  46659. maxValue = Math.min(max, maxValue);
  46660. if (d > maxValue) {
  46661. return false;
  46662. }
  46663. }
  46664. if (Math.abs(this.direction.y) < 0.0000001) {
  46665. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  46666. return false;
  46667. }
  46668. }
  46669. else {
  46670. inv = 1.0 / this.direction.y;
  46671. min = (minimum.y - this.origin.y) * inv;
  46672. max = (maximum.y - this.origin.y) * inv;
  46673. if (max === -Infinity) {
  46674. max = Infinity;
  46675. }
  46676. if (min > max) {
  46677. temp = min;
  46678. min = max;
  46679. max = temp;
  46680. }
  46681. d = Math.max(min, d);
  46682. maxValue = Math.min(max, maxValue);
  46683. if (d > maxValue) {
  46684. return false;
  46685. }
  46686. }
  46687. if (Math.abs(this.direction.z) < 0.0000001) {
  46688. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  46689. return false;
  46690. }
  46691. }
  46692. else {
  46693. inv = 1.0 / this.direction.z;
  46694. min = (minimum.z - this.origin.z) * inv;
  46695. max = (maximum.z - this.origin.z) * inv;
  46696. if (max === -Infinity) {
  46697. max = Infinity;
  46698. }
  46699. if (min > max) {
  46700. temp = min;
  46701. min = max;
  46702. max = temp;
  46703. }
  46704. d = Math.max(min, d);
  46705. maxValue = Math.min(max, maxValue);
  46706. if (d > maxValue) {
  46707. return false;
  46708. }
  46709. }
  46710. return true;
  46711. };
  46712. Ray.prototype.intersectsBox = function (box) {
  46713. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  46714. };
  46715. Ray.prototype.intersectsSphere = function (sphere) {
  46716. var x = sphere.center.x - this.origin.x;
  46717. var y = sphere.center.y - this.origin.y;
  46718. var z = sphere.center.z - this.origin.z;
  46719. var pyth = (x * x) + (y * y) + (z * z);
  46720. var rr = sphere.radius * sphere.radius;
  46721. if (pyth <= rr) {
  46722. return true;
  46723. }
  46724. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  46725. if (dot < 0.0) {
  46726. return false;
  46727. }
  46728. var temp = pyth - (dot * dot);
  46729. return temp <= rr;
  46730. };
  46731. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  46732. if (!this._edge1) {
  46733. this._edge1 = BABYLON.Vector3.Zero();
  46734. this._edge2 = BABYLON.Vector3.Zero();
  46735. this._pvec = BABYLON.Vector3.Zero();
  46736. this._tvec = BABYLON.Vector3.Zero();
  46737. this._qvec = BABYLON.Vector3.Zero();
  46738. }
  46739. vertex1.subtractToRef(vertex0, this._edge1);
  46740. vertex2.subtractToRef(vertex0, this._edge2);
  46741. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  46742. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  46743. if (det === 0) {
  46744. return null;
  46745. }
  46746. var invdet = 1 / det;
  46747. this.origin.subtractToRef(vertex0, this._tvec);
  46748. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  46749. if (bu < 0 || bu > 1.0) {
  46750. return null;
  46751. }
  46752. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  46753. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  46754. if (bv < 0 || bu + bv > 1.0) {
  46755. return null;
  46756. }
  46757. //check if the distance is longer than the predefined length.
  46758. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  46759. if (distance > this.length) {
  46760. return null;
  46761. }
  46762. return new BABYLON.IntersectionInfo(bu, bv, distance);
  46763. };
  46764. Ray.prototype.intersectsPlane = function (plane) {
  46765. var distance;
  46766. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  46767. if (Math.abs(result1) < 9.99999997475243E-07) {
  46768. return null;
  46769. }
  46770. else {
  46771. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  46772. distance = (-plane.d - result2) / result1;
  46773. if (distance < 0.0) {
  46774. if (distance < -9.99999997475243E-07) {
  46775. return null;
  46776. }
  46777. else {
  46778. return 0;
  46779. }
  46780. }
  46781. return distance;
  46782. }
  46783. };
  46784. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  46785. var tm = BABYLON.Tmp.Matrix[0];
  46786. mesh.getWorldMatrix().invertToRef(tm);
  46787. if (this._tmpRay) {
  46788. Ray.TransformToRef(this, tm, this._tmpRay);
  46789. }
  46790. else {
  46791. this._tmpRay = Ray.Transform(this, tm);
  46792. }
  46793. return mesh.intersects(this._tmpRay, fastCheck);
  46794. };
  46795. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  46796. if (results) {
  46797. results.length = 0;
  46798. }
  46799. else {
  46800. results = [];
  46801. }
  46802. for (var i = 0; i < meshes.length; i++) {
  46803. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  46804. if (pickInfo.hit) {
  46805. results.push(pickInfo);
  46806. }
  46807. }
  46808. results.sort(this._comparePickingInfo);
  46809. return results;
  46810. };
  46811. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  46812. if (pickingInfoA.distance < pickingInfoB.distance) {
  46813. return -1;
  46814. }
  46815. else if (pickingInfoA.distance > pickingInfoB.distance) {
  46816. return 1;
  46817. }
  46818. else {
  46819. return 0;
  46820. }
  46821. };
  46822. /**
  46823. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  46824. * @param sega the first point of the segment to test the intersection against
  46825. * @param segb the second point of the segment to test the intersection against
  46826. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  46827. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  46828. */
  46829. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  46830. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  46831. var u = segb.subtract(sega);
  46832. var v = rsegb.subtract(this.origin);
  46833. var w = sega.subtract(this.origin);
  46834. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  46835. var b = BABYLON.Vector3.Dot(u, v);
  46836. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  46837. var d = BABYLON.Vector3.Dot(u, w);
  46838. var e = BABYLON.Vector3.Dot(v, w);
  46839. var D = a * c - b * b; // always >= 0
  46840. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  46841. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  46842. // compute the line parameters of the two closest points
  46843. if (D < Ray.smallnum) {
  46844. sN = 0.0; // force using point P0 on segment S1
  46845. sD = 1.0; // to prevent possible division by 0.0 later
  46846. tN = e;
  46847. tD = c;
  46848. }
  46849. else {
  46850. sN = (b * e - c * d);
  46851. tN = (a * e - b * d);
  46852. if (sN < 0.0) {
  46853. sN = 0.0;
  46854. tN = e;
  46855. tD = c;
  46856. }
  46857. else if (sN > sD) {
  46858. sN = sD;
  46859. tN = e + b;
  46860. tD = c;
  46861. }
  46862. }
  46863. if (tN < 0.0) {
  46864. tN = 0.0;
  46865. // recompute sc for this edge
  46866. if (-d < 0.0) {
  46867. sN = 0.0;
  46868. }
  46869. else if (-d > a)
  46870. sN = sD;
  46871. else {
  46872. sN = -d;
  46873. sD = a;
  46874. }
  46875. }
  46876. else if (tN > tD) {
  46877. tN = tD;
  46878. // recompute sc for this edge
  46879. if ((-d + b) < 0.0) {
  46880. sN = 0;
  46881. }
  46882. else if ((-d + b) > a) {
  46883. sN = sD;
  46884. }
  46885. else {
  46886. sN = (-d + b);
  46887. sD = a;
  46888. }
  46889. }
  46890. // finally do the division to get sc and tc
  46891. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  46892. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  46893. // get the difference of the two closest points
  46894. var qtc = v.multiplyByFloats(tc, tc, tc);
  46895. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  46896. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  46897. if (isIntersected) {
  46898. return qtc.length();
  46899. }
  46900. return -1;
  46901. };
  46902. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  46903. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  46904. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  46905. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  46906. this.direction.normalize();
  46907. return this;
  46908. };
  46909. // Statics
  46910. Ray.Zero = function () {
  46911. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  46912. };
  46913. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  46914. var result = Ray.Zero();
  46915. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  46916. };
  46917. /**
  46918. * 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
  46919. * transformed to the given world matrix.
  46920. * @param origin The origin point
  46921. * @param end The end point
  46922. * @param world a matrix to transform the ray to. Default is the identity matrix.
  46923. */
  46924. Ray.CreateNewFromTo = function (origin, end, world) {
  46925. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  46926. var direction = end.subtract(origin);
  46927. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  46928. direction.normalize();
  46929. return Ray.Transform(new Ray(origin, direction, length), world);
  46930. };
  46931. Ray.Transform = function (ray, matrix) {
  46932. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  46933. Ray.TransformToRef(ray, matrix, result);
  46934. return result;
  46935. };
  46936. Ray.TransformToRef = function (ray, matrix, result) {
  46937. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  46938. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  46939. result.length = ray.length;
  46940. var dir = result.direction;
  46941. var len = dir.length();
  46942. if (!(len === 0 || len === 1)) {
  46943. var num = 1.0 / len;
  46944. dir.x *= num;
  46945. dir.y *= num;
  46946. dir.z *= num;
  46947. result.length *= len;
  46948. }
  46949. };
  46950. Ray.smallnum = 0.00000001;
  46951. Ray.rayl = 10e8;
  46952. return Ray;
  46953. }());
  46954. BABYLON.Ray = Ray;
  46955. })(BABYLON || (BABYLON = {}));
  46956. //# sourceMappingURL=babylon.ray.js.map
  46957. var BABYLON;
  46958. (function (BABYLON) {
  46959. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  46960. if (boxMin.x > sphereCenter.x + sphereRadius)
  46961. return false;
  46962. if (sphereCenter.x - sphereRadius > boxMax.x)
  46963. return false;
  46964. if (boxMin.y > sphereCenter.y + sphereRadius)
  46965. return false;
  46966. if (sphereCenter.y - sphereRadius > boxMax.y)
  46967. return false;
  46968. if (boxMin.z > sphereCenter.z + sphereRadius)
  46969. return false;
  46970. if (sphereCenter.z - sphereRadius > boxMax.z)
  46971. return false;
  46972. return true;
  46973. };
  46974. var getLowestRoot = (function () {
  46975. var result = { root: 0, found: false };
  46976. return function (a, b, c, maxR) {
  46977. result.root = 0;
  46978. result.found = false;
  46979. var determinant = b * b - 4.0 * a * c;
  46980. if (determinant < 0)
  46981. return result;
  46982. var sqrtD = Math.sqrt(determinant);
  46983. var r1 = (-b - sqrtD) / (2.0 * a);
  46984. var r2 = (-b + sqrtD) / (2.0 * a);
  46985. if (r1 > r2) {
  46986. var temp = r2;
  46987. r2 = r1;
  46988. r1 = temp;
  46989. }
  46990. if (r1 > 0 && r1 < maxR) {
  46991. result.root = r1;
  46992. result.found = true;
  46993. return result;
  46994. }
  46995. if (r2 > 0 && r2 < maxR) {
  46996. result.root = r2;
  46997. result.found = true;
  46998. return result;
  46999. }
  47000. return result;
  47001. };
  47002. })();
  47003. var Collider = /** @class */ (function () {
  47004. function Collider() {
  47005. this._collisionPoint = BABYLON.Vector3.Zero();
  47006. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  47007. this._tempVector = BABYLON.Vector3.Zero();
  47008. this._tempVector2 = BABYLON.Vector3.Zero();
  47009. this._tempVector3 = BABYLON.Vector3.Zero();
  47010. this._tempVector4 = BABYLON.Vector3.Zero();
  47011. this._edge = BABYLON.Vector3.Zero();
  47012. this._baseToVertex = BABYLON.Vector3.Zero();
  47013. this._destinationPoint = BABYLON.Vector3.Zero();
  47014. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  47015. this._displacementVector = BABYLON.Vector3.Zero();
  47016. this._radius = BABYLON.Vector3.One();
  47017. this._retry = 0;
  47018. this._basePointWorld = BABYLON.Vector3.Zero();
  47019. this._velocityWorld = BABYLON.Vector3.Zero();
  47020. this._normalizedVelocity = BABYLON.Vector3.Zero();
  47021. this._collisionMask = -1;
  47022. }
  47023. Object.defineProperty(Collider.prototype, "collisionMask", {
  47024. get: function () {
  47025. return this._collisionMask;
  47026. },
  47027. set: function (mask) {
  47028. this._collisionMask = !isNaN(mask) ? mask : -1;
  47029. },
  47030. enumerable: true,
  47031. configurable: true
  47032. });
  47033. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  47034. /**
  47035. * Gets the plane normal used to compute the sliding response (in local space)
  47036. */
  47037. get: function () {
  47038. return this._slidePlaneNormal;
  47039. },
  47040. enumerable: true,
  47041. configurable: true
  47042. });
  47043. // Methods
  47044. Collider.prototype._initialize = function (source, dir, e) {
  47045. this._velocity = dir;
  47046. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  47047. this._basePoint = source;
  47048. source.multiplyToRef(this._radius, this._basePointWorld);
  47049. dir.multiplyToRef(this._radius, this._velocityWorld);
  47050. this._velocityWorldLength = this._velocityWorld.length();
  47051. this._epsilon = e;
  47052. this.collisionFound = false;
  47053. };
  47054. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  47055. pa.subtractToRef(point, this._tempVector);
  47056. pb.subtractToRef(point, this._tempVector2);
  47057. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  47058. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  47059. if (d < 0)
  47060. return false;
  47061. pc.subtractToRef(point, this._tempVector3);
  47062. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  47063. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  47064. if (d < 0)
  47065. return false;
  47066. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  47067. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  47068. return d >= 0;
  47069. };
  47070. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  47071. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  47072. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  47073. if (distance > this._velocityWorldLength + max + sphereRadius) {
  47074. return false;
  47075. }
  47076. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  47077. return false;
  47078. return true;
  47079. };
  47080. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  47081. var t0;
  47082. var embeddedInPlane = false;
  47083. //defensive programming, actually not needed.
  47084. if (!trianglePlaneArray) {
  47085. trianglePlaneArray = [];
  47086. }
  47087. if (!trianglePlaneArray[faceIndex]) {
  47088. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  47089. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  47090. }
  47091. var trianglePlane = trianglePlaneArray[faceIndex];
  47092. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  47093. return;
  47094. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  47095. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  47096. if (normalDotVelocity == 0) {
  47097. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  47098. return;
  47099. embeddedInPlane = true;
  47100. t0 = 0;
  47101. }
  47102. else {
  47103. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  47104. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  47105. if (t0 > t1) {
  47106. var temp = t1;
  47107. t1 = t0;
  47108. t0 = temp;
  47109. }
  47110. if (t0 > 1.0 || t1 < 0.0)
  47111. return;
  47112. if (t0 < 0)
  47113. t0 = 0;
  47114. if (t0 > 1.0)
  47115. t0 = 1.0;
  47116. }
  47117. this._collisionPoint.copyFromFloats(0, 0, 0);
  47118. var found = false;
  47119. var t = 1.0;
  47120. if (!embeddedInPlane) {
  47121. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  47122. this._velocity.scaleToRef(t0, this._tempVector);
  47123. this._planeIntersectionPoint.addInPlace(this._tempVector);
  47124. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  47125. found = true;
  47126. t = t0;
  47127. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  47128. }
  47129. }
  47130. if (!found) {
  47131. var velocitySquaredLength = this._velocity.lengthSquared();
  47132. var a = velocitySquaredLength;
  47133. this._basePoint.subtractToRef(p1, this._tempVector);
  47134. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  47135. var c = this._tempVector.lengthSquared() - 1.0;
  47136. var lowestRoot = getLowestRoot(a, b, c, t);
  47137. if (lowestRoot.found) {
  47138. t = lowestRoot.root;
  47139. found = true;
  47140. this._collisionPoint.copyFrom(p1);
  47141. }
  47142. this._basePoint.subtractToRef(p2, this._tempVector);
  47143. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  47144. c = this._tempVector.lengthSquared() - 1.0;
  47145. lowestRoot = getLowestRoot(a, b, c, t);
  47146. if (lowestRoot.found) {
  47147. t = lowestRoot.root;
  47148. found = true;
  47149. this._collisionPoint.copyFrom(p2);
  47150. }
  47151. this._basePoint.subtractToRef(p3, this._tempVector);
  47152. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  47153. c = this._tempVector.lengthSquared() - 1.0;
  47154. lowestRoot = getLowestRoot(a, b, c, t);
  47155. if (lowestRoot.found) {
  47156. t = lowestRoot.root;
  47157. found = true;
  47158. this._collisionPoint.copyFrom(p3);
  47159. }
  47160. p2.subtractToRef(p1, this._edge);
  47161. p1.subtractToRef(this._basePoint, this._baseToVertex);
  47162. var edgeSquaredLength = this._edge.lengthSquared();
  47163. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  47164. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  47165. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  47166. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  47167. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  47168. lowestRoot = getLowestRoot(a, b, c, t);
  47169. if (lowestRoot.found) {
  47170. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  47171. if (f >= 0.0 && f <= 1.0) {
  47172. t = lowestRoot.root;
  47173. found = true;
  47174. this._edge.scaleInPlace(f);
  47175. p1.addToRef(this._edge, this._collisionPoint);
  47176. }
  47177. }
  47178. p3.subtractToRef(p2, this._edge);
  47179. p2.subtractToRef(this._basePoint, this._baseToVertex);
  47180. edgeSquaredLength = this._edge.lengthSquared();
  47181. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  47182. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  47183. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  47184. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  47185. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  47186. lowestRoot = getLowestRoot(a, b, c, t);
  47187. if (lowestRoot.found) {
  47188. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  47189. if (f >= 0.0 && f <= 1.0) {
  47190. t = lowestRoot.root;
  47191. found = true;
  47192. this._edge.scaleInPlace(f);
  47193. p2.addToRef(this._edge, this._collisionPoint);
  47194. }
  47195. }
  47196. p1.subtractToRef(p3, this._edge);
  47197. p3.subtractToRef(this._basePoint, this._baseToVertex);
  47198. edgeSquaredLength = this._edge.lengthSquared();
  47199. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  47200. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  47201. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  47202. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  47203. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  47204. lowestRoot = getLowestRoot(a, b, c, t);
  47205. if (lowestRoot.found) {
  47206. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  47207. if (f >= 0.0 && f <= 1.0) {
  47208. t = lowestRoot.root;
  47209. found = true;
  47210. this._edge.scaleInPlace(f);
  47211. p3.addToRef(this._edge, this._collisionPoint);
  47212. }
  47213. }
  47214. }
  47215. if (found) {
  47216. var distToCollision = t * this._velocity.length();
  47217. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  47218. if (!this.intersectionPoint) {
  47219. this.intersectionPoint = this._collisionPoint.clone();
  47220. }
  47221. else {
  47222. this.intersectionPoint.copyFrom(this._collisionPoint);
  47223. }
  47224. this._nearestDistance = distToCollision;
  47225. this.collisionFound = true;
  47226. }
  47227. }
  47228. };
  47229. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  47230. for (var i = indexStart; i < indexEnd; i += 3) {
  47231. var p1 = pts[indices[i] - decal];
  47232. var p2 = pts[indices[i + 1] - decal];
  47233. var p3 = pts[indices[i + 2] - decal];
  47234. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  47235. }
  47236. };
  47237. Collider.prototype._getResponse = function (pos, vel) {
  47238. pos.addToRef(vel, this._destinationPoint);
  47239. vel.scaleInPlace((this._nearestDistance / vel.length()));
  47240. this._basePoint.addToRef(vel, pos);
  47241. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  47242. this._slidePlaneNormal.normalize();
  47243. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  47244. pos.addInPlace(this._displacementVector);
  47245. this.intersectionPoint.addInPlace(this._displacementVector);
  47246. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  47247. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  47248. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  47249. };
  47250. return Collider;
  47251. }());
  47252. BABYLON.Collider = Collider;
  47253. })(BABYLON || (BABYLON = {}));
  47254. //# sourceMappingURL=babylon.collider.js.map
  47255. var BABYLON;
  47256. (function (BABYLON) {
  47257. //WebWorker code will be inserted to this variable.
  47258. BABYLON.CollisionWorker = "";
  47259. var WorkerTaskType;
  47260. (function (WorkerTaskType) {
  47261. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  47262. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  47263. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  47264. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  47265. var WorkerReplyType;
  47266. (function (WorkerReplyType) {
  47267. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  47268. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  47269. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  47270. var CollisionCoordinatorWorker = /** @class */ (function () {
  47271. function CollisionCoordinatorWorker() {
  47272. var _this = this;
  47273. this._scaledPosition = BABYLON.Vector3.Zero();
  47274. this._scaledVelocity = BABYLON.Vector3.Zero();
  47275. this.onMeshUpdated = function (transformNode) {
  47276. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  47277. };
  47278. this.onGeometryUpdated = function (geometry) {
  47279. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  47280. };
  47281. this._afterRender = function () {
  47282. if (!_this._init)
  47283. return;
  47284. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  47285. return;
  47286. }
  47287. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  47288. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  47289. if (_this._runningUpdated > 4) {
  47290. return;
  47291. }
  47292. ++_this._runningUpdated;
  47293. var payload = {
  47294. updatedMeshes: _this._addUpdateMeshesList,
  47295. updatedGeometries: _this._addUpdateGeometriesList,
  47296. removedGeometries: _this._toRemoveGeometryArray,
  47297. removedMeshes: _this._toRemoveMeshesArray
  47298. };
  47299. var message = {
  47300. payload: payload,
  47301. taskType: WorkerTaskType.UPDATE
  47302. };
  47303. var serializable = [];
  47304. for (var id in payload.updatedGeometries) {
  47305. if (payload.updatedGeometries.hasOwnProperty(id)) {
  47306. //prepare transferables
  47307. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  47308. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  47309. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  47310. }
  47311. }
  47312. _this._worker.postMessage(message, serializable);
  47313. _this._addUpdateMeshesList = {};
  47314. _this._addUpdateGeometriesList = {};
  47315. _this._toRemoveGeometryArray = [];
  47316. _this._toRemoveMeshesArray = [];
  47317. };
  47318. this._onMessageFromWorker = function (e) {
  47319. var returnData = e.data;
  47320. if (returnData.error != WorkerReplyType.SUCCESS) {
  47321. //TODO what errors can be returned from the worker?
  47322. BABYLON.Tools.Warn("error returned from worker!");
  47323. return;
  47324. }
  47325. switch (returnData.taskType) {
  47326. case WorkerTaskType.INIT:
  47327. _this._init = true;
  47328. //Update the worked with ALL of the scene's current state
  47329. _this._scene.meshes.forEach(function (mesh) {
  47330. _this.onMeshAdded(mesh);
  47331. });
  47332. _this._scene.getGeometries().forEach(function (geometry) {
  47333. _this.onGeometryAdded(geometry);
  47334. });
  47335. break;
  47336. case WorkerTaskType.UPDATE:
  47337. _this._runningUpdated--;
  47338. break;
  47339. case WorkerTaskType.COLLIDE:
  47340. var returnPayload = returnData.payload;
  47341. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  47342. return;
  47343. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  47344. if (callback) {
  47345. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  47346. if (mesh) {
  47347. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  47348. }
  47349. }
  47350. //cleanup
  47351. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  47352. break;
  47353. }
  47354. };
  47355. this._collisionsCallbackArray = [];
  47356. this._init = false;
  47357. this._runningUpdated = 0;
  47358. this._addUpdateMeshesList = {};
  47359. this._addUpdateGeometriesList = {};
  47360. this._toRemoveGeometryArray = [];
  47361. this._toRemoveMeshesArray = [];
  47362. }
  47363. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  47364. if (!this._init)
  47365. return;
  47366. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  47367. return;
  47368. position.divideToRef(collider._radius, this._scaledPosition);
  47369. displacement.divideToRef(collider._radius, this._scaledVelocity);
  47370. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  47371. var payload = {
  47372. collider: {
  47373. position: this._scaledPosition.asArray(),
  47374. velocity: this._scaledVelocity.asArray(),
  47375. radius: collider._radius.asArray()
  47376. },
  47377. collisionId: collisionIndex,
  47378. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  47379. maximumRetry: maximumRetry
  47380. };
  47381. var message = {
  47382. payload: payload,
  47383. taskType: WorkerTaskType.COLLIDE
  47384. };
  47385. this._worker.postMessage(message);
  47386. };
  47387. CollisionCoordinatorWorker.prototype.init = function (scene) {
  47388. this._scene = scene;
  47389. this._scene.registerAfterRender(this._afterRender);
  47390. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  47391. this._worker = new Worker(workerUrl);
  47392. this._worker.onmessage = this._onMessageFromWorker;
  47393. var message = {
  47394. payload: {},
  47395. taskType: WorkerTaskType.INIT
  47396. };
  47397. this._worker.postMessage(message);
  47398. };
  47399. CollisionCoordinatorWorker.prototype.destroy = function () {
  47400. this._scene.unregisterAfterRender(this._afterRender);
  47401. this._worker.terminate();
  47402. };
  47403. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  47404. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  47405. this.onMeshUpdated(mesh);
  47406. };
  47407. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  47408. this._toRemoveMeshesArray.push(mesh.uniqueId);
  47409. };
  47410. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  47411. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  47412. geometry.onGeometryUpdated = this.onGeometryUpdated;
  47413. this.onGeometryUpdated(geometry);
  47414. };
  47415. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  47416. this._toRemoveGeometryArray.push(geometry.id);
  47417. };
  47418. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  47419. var submeshes = [];
  47420. if (mesh.subMeshes) {
  47421. submeshes = mesh.subMeshes.map(function (sm, idx) {
  47422. var boundingInfo = sm.getBoundingInfo();
  47423. return {
  47424. position: idx,
  47425. verticesStart: sm.verticesStart,
  47426. verticesCount: sm.verticesCount,
  47427. indexStart: sm.indexStart,
  47428. indexCount: sm.indexCount,
  47429. hasMaterial: !!sm.getMaterial(),
  47430. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  47431. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  47432. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  47433. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  47434. };
  47435. });
  47436. }
  47437. var geometryId = null;
  47438. if (mesh instanceof BABYLON.Mesh) {
  47439. var geometry = mesh.geometry;
  47440. geometryId = geometry ? geometry.id : null;
  47441. }
  47442. else if (mesh instanceof BABYLON.InstancedMesh) {
  47443. var geometry = mesh.sourceMesh.geometry;
  47444. geometryId = geometry ? geometry.id : null;
  47445. }
  47446. var boundingInfo = mesh.getBoundingInfo();
  47447. return {
  47448. uniqueId: mesh.uniqueId,
  47449. id: mesh.id,
  47450. name: mesh.name,
  47451. geometryId: geometryId,
  47452. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  47453. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  47454. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  47455. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  47456. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  47457. subMeshes: submeshes,
  47458. checkCollisions: mesh.checkCollisions
  47459. };
  47460. };
  47461. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  47462. return {
  47463. id: geometry.id,
  47464. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  47465. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  47466. indices: new Uint32Array(geometry.getIndices() || []),
  47467. };
  47468. };
  47469. return CollisionCoordinatorWorker;
  47470. }());
  47471. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  47472. var CollisionCoordinatorLegacy = /** @class */ (function () {
  47473. function CollisionCoordinatorLegacy() {
  47474. this._scaledPosition = BABYLON.Vector3.Zero();
  47475. this._scaledVelocity = BABYLON.Vector3.Zero();
  47476. this._finalPosition = BABYLON.Vector3.Zero();
  47477. }
  47478. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  47479. position.divideToRef(collider._radius, this._scaledPosition);
  47480. displacement.divideToRef(collider._radius, this._scaledVelocity);
  47481. collider.collidedMesh = null;
  47482. collider._retry = 0;
  47483. collider._initialVelocity = this._scaledVelocity;
  47484. collider._initialPosition = this._scaledPosition;
  47485. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  47486. this._finalPosition.multiplyInPlace(collider._radius);
  47487. //run the callback
  47488. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  47489. };
  47490. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  47491. this._scene = scene;
  47492. };
  47493. CollisionCoordinatorLegacy.prototype.destroy = function () {
  47494. //Legacy need no destruction method.
  47495. };
  47496. //No update in legacy mode
  47497. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  47498. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  47499. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  47500. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  47501. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  47502. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  47503. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  47504. if (excludedMesh === void 0) { excludedMesh = null; }
  47505. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  47506. if (collider._retry >= maximumRetry) {
  47507. finalPosition.copyFrom(position);
  47508. return;
  47509. }
  47510. // Check if this is a mesh else camera or -1
  47511. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  47512. collider._initialize(position, velocity, closeDistance);
  47513. // Check all meshes
  47514. for (var index = 0; index < this._scene.meshes.length; index++) {
  47515. var mesh = this._scene.meshes[index];
  47516. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  47517. mesh._checkCollision(collider);
  47518. }
  47519. }
  47520. if (!collider.collisionFound) {
  47521. position.addToRef(velocity, finalPosition);
  47522. return;
  47523. }
  47524. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  47525. collider._getResponse(position, velocity);
  47526. }
  47527. if (velocity.length() <= closeDistance) {
  47528. finalPosition.copyFrom(position);
  47529. return;
  47530. }
  47531. collider._retry++;
  47532. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  47533. };
  47534. return CollisionCoordinatorLegacy;
  47535. }());
  47536. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  47537. })(BABYLON || (BABYLON = {}));
  47538. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  47539. var BABYLON;
  47540. (function (BABYLON) {
  47541. /**
  47542. * A particle represents one of the element emitted by a particle system.
  47543. * This is mainly define by its coordinates, direction, velocity and age.
  47544. */
  47545. var Particle = /** @class */ (function () {
  47546. /**
  47547. * Creates a new instance of @see Particle
  47548. * @param particleSystem the particle system the particle belongs to
  47549. */
  47550. function Particle(particleSystem) {
  47551. this.particleSystem = particleSystem;
  47552. /**
  47553. * The world position of the particle in the scene.
  47554. */
  47555. this.position = BABYLON.Vector3.Zero();
  47556. /**
  47557. * The world direction of the particle in the scene.
  47558. */
  47559. this.direction = BABYLON.Vector3.Zero();
  47560. /**
  47561. * The color of the particle.
  47562. */
  47563. this.color = new BABYLON.Color4(0, 0, 0, 0);
  47564. /**
  47565. * The color change of the particle per step.
  47566. */
  47567. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  47568. /**
  47569. * Defines how long will the life of the particle be.
  47570. */
  47571. this.lifeTime = 1.0;
  47572. /**
  47573. * The current age of the particle.
  47574. */
  47575. this.age = 0;
  47576. /**
  47577. * The current size of the particle.
  47578. */
  47579. this.size = 0;
  47580. /**
  47581. * The current angle of the particle.
  47582. */
  47583. this.angle = 0;
  47584. /**
  47585. * Defines how fast is the angle changing.
  47586. */
  47587. this.angularSpeed = 0;
  47588. /**
  47589. * Defines the cell index used by the particle to be rendered from a sprite.
  47590. */
  47591. this.cellIndex = 0;
  47592. this._currentFrameCounter = 0;
  47593. if (!this.particleSystem.isAnimationSheetEnabled) {
  47594. return;
  47595. }
  47596. this.cellIndex = this.particleSystem.startSpriteCellID;
  47597. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  47598. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  47599. }
  47600. else {
  47601. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  47602. }
  47603. }
  47604. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  47605. // (ageOffset / scaledUpdateSpeed) / available cells
  47606. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  47607. this._currentFrameCounter += scaledUpdateSpeed;
  47608. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  47609. this._currentFrameCounter = 0;
  47610. this.cellIndex++;
  47611. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  47612. this.cellIndex = this.particleSystem.endSpriteCellID;
  47613. }
  47614. }
  47615. };
  47616. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  47617. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  47618. this.cellIndex++;
  47619. this._currentFrameCounter = 0;
  47620. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  47621. if (this.particleSystem.spriteCellLoop) {
  47622. this.cellIndex = this.particleSystem.startSpriteCellID;
  47623. }
  47624. else {
  47625. this.cellIndex = this.particleSystem.endSpriteCellID;
  47626. }
  47627. }
  47628. }
  47629. else {
  47630. this._currentFrameCounter++;
  47631. }
  47632. };
  47633. /**
  47634. * Copy the properties of particle to another one.
  47635. * @param other the particle to copy the information to.
  47636. */
  47637. Particle.prototype.copyTo = function (other) {
  47638. other.position.copyFrom(this.position);
  47639. other.direction.copyFrom(this.direction);
  47640. other.color.copyFrom(this.color);
  47641. other.colorStep.copyFrom(this.colorStep);
  47642. other.lifeTime = this.lifeTime;
  47643. other.age = this.age;
  47644. other.size = this.size;
  47645. other.angle = this.angle;
  47646. other.angularSpeed = this.angularSpeed;
  47647. other.particleSystem = this.particleSystem;
  47648. other.cellIndex = this.cellIndex;
  47649. };
  47650. return Particle;
  47651. }());
  47652. BABYLON.Particle = Particle;
  47653. })(BABYLON || (BABYLON = {}));
  47654. //# sourceMappingURL=babylon.particle.js.map
  47655. var BABYLON;
  47656. (function (BABYLON) {
  47657. /**
  47658. * This represents a particle system in Babylon.
  47659. * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.
  47660. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  47661. * @example https://doc.babylonjs.com/babylon101/particles
  47662. */
  47663. var ParticleSystem = /** @class */ (function () {
  47664. /**
  47665. * Instantiates a particle system.
  47666. * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.
  47667. * @param name The name of the particle system
  47668. * @param capacity The max number of particles alive at the same time
  47669. * @param scene The scene the particle system belongs to
  47670. * @param customEffect a custom effect used to change the way particles are rendered by default
  47671. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  47672. * @param epsilon Offset used to render the particles
  47673. */
  47674. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  47675. if (customEffect === void 0) { customEffect = null; }
  47676. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  47677. if (epsilon === void 0) { epsilon = 0.01; }
  47678. var _this = this;
  47679. /**
  47680. * List of animations used by the particle system.
  47681. */
  47682. this.animations = [];
  47683. /**
  47684. * The rendering group used by the Particle system to chose when to render.
  47685. */
  47686. this.renderingGroupId = 0;
  47687. /**
  47688. * The emitter represents the Mesh or position we are attaching the particle system to.
  47689. */
  47690. this.emitter = null;
  47691. /**
  47692. * The density of particles, the rate of particle flow
  47693. */
  47694. this.emitRate = 10;
  47695. /**
  47696. * If you want to launch only a few particles at once, that can be done, as well.
  47697. */
  47698. this.manualEmitCount = -1;
  47699. /**
  47700. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  47701. */
  47702. this.updateSpeed = 0.01;
  47703. /**
  47704. * The amount of time the particle system is running (depends of the overall speed above).
  47705. */
  47706. this.targetStopDuration = 0;
  47707. /**
  47708. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  47709. */
  47710. this.disposeOnStop = false;
  47711. /**
  47712. * Minimum power of emitting particles.
  47713. */
  47714. this.minEmitPower = 1;
  47715. /**
  47716. * Maximum power of emitting particles.
  47717. */
  47718. this.maxEmitPower = 1;
  47719. /**
  47720. * Minimum life time of emitting particles.
  47721. */
  47722. this.minLifeTime = 1;
  47723. /**
  47724. * Maximum life time of emitting particles.
  47725. */
  47726. this.maxLifeTime = 1;
  47727. /**
  47728. * Minimum Size of emitting particles.
  47729. */
  47730. this.minSize = 1;
  47731. /**
  47732. * Maximum Size of emitting particles.
  47733. */
  47734. this.maxSize = 1;
  47735. /**
  47736. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  47737. */
  47738. this.minAngularSpeed = 0;
  47739. /**
  47740. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  47741. */
  47742. this.maxAngularSpeed = 0;
  47743. /**
  47744. * The layer mask we are rendering the particles through.
  47745. */
  47746. this.layerMask = 0x0FFFFFFF;
  47747. /**
  47748. * This can help using your own shader to render the particle system.
  47749. * The according effect will be created
  47750. */
  47751. this.customShader = null;
  47752. /**
  47753. * By default particle system starts as soon as they are created. This prevents the
  47754. * automatic start to happen and let you decide when to start emitting particles.
  47755. */
  47756. this.preventAutoStart = false;
  47757. /**
  47758. * Callback triggered when the particle animation is ending.
  47759. */
  47760. this.onAnimationEnd = null;
  47761. /**
  47762. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  47763. */
  47764. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  47765. /**
  47766. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  47767. * to override the particles.
  47768. */
  47769. this.forceDepthWrite = false;
  47770. /**
  47771. * You can use gravity if you want to give an orientation to your particles.
  47772. */
  47773. this.gravity = BABYLON.Vector3.Zero();
  47774. /**
  47775. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  47776. */
  47777. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  47778. /**
  47779. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  47780. */
  47781. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  47782. /**
  47783. * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  47784. */
  47785. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  47786. /**
  47787. * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  47788. */
  47789. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47790. /**
  47791. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  47792. */
  47793. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  47794. /**
  47795. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  47796. */
  47797. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  47798. /**
  47799. * Color the particle will have at the end of its lifetime.
  47800. */
  47801. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  47802. /**
  47803. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  47804. */
  47805. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  47806. /**
  47807. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  47808. */
  47809. this.spriteCellLoop = true;
  47810. /**
  47811. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  47812. */
  47813. this.spriteCellChangeSpeed = 0;
  47814. /**
  47815. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  47816. */
  47817. this.startSpriteCellID = 0;
  47818. /**
  47819. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  47820. */
  47821. this.endSpriteCellID = 0;
  47822. /**
  47823. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  47824. */
  47825. this.spriteCellWidth = 0;
  47826. /**
  47827. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  47828. */
  47829. this.spriteCellHeight = 0;
  47830. /**
  47831. * An event triggered when the system is disposed.
  47832. */
  47833. this.onDisposeObservable = new BABYLON.Observable();
  47834. this._particles = new Array();
  47835. this._stockParticles = new Array();
  47836. this._newPartsExcess = 0;
  47837. this._vertexBuffers = {};
  47838. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  47839. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  47840. this._scaledDirection = BABYLON.Vector3.Zero();
  47841. this._scaledGravity = BABYLON.Vector3.Zero();
  47842. this._currentRenderId = -1;
  47843. this._started = false;
  47844. this._stopped = false;
  47845. this._actualFrame = 0;
  47846. this._vertexBufferSize = 11;
  47847. this._appendParticleVertexes = null;
  47848. this.id = name;
  47849. this.name = name;
  47850. this._capacity = capacity;
  47851. this._epsilon = epsilon;
  47852. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  47853. if (isAnimationSheetEnabled) {
  47854. this._vertexBufferSize = 12;
  47855. }
  47856. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  47857. this._customEffect = customEffect;
  47858. scene.particleSystems.push(this);
  47859. this._createIndexBuffer();
  47860. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  47861. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  47862. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  47863. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  47864. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  47865. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  47866. if (this._isAnimationSheetEnabled) {
  47867. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  47868. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  47869. }
  47870. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  47871. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  47872. this._vertexBuffers["options"] = options;
  47873. // Default behaviors
  47874. this.particleEmitterType = new BABYLON.BoxParticleEmitter(this);
  47875. this.updateFunction = function (particles) {
  47876. for (var index = 0; index < particles.length; index++) {
  47877. var particle = particles[index];
  47878. particle.age += _this._scaledUpdateSpeed;
  47879. if (particle.age >= particle.lifeTime) {
  47880. _this.recycleParticle(particle);
  47881. index--;
  47882. continue;
  47883. }
  47884. else {
  47885. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  47886. particle.color.addInPlace(_this._scaledColorStep);
  47887. if (particle.color.a < 0)
  47888. particle.color.a = 0;
  47889. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  47890. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  47891. particle.position.addInPlace(_this._scaledDirection);
  47892. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  47893. particle.direction.addInPlace(_this._scaledGravity);
  47894. if (_this._isAnimationSheetEnabled) {
  47895. particle.updateCellIndex(_this._scaledUpdateSpeed);
  47896. }
  47897. }
  47898. }
  47899. };
  47900. }
  47901. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  47902. /**
  47903. * Sets a callback that will be triggered when the system is disposed.
  47904. */
  47905. set: function (callback) {
  47906. if (this._onDisposeObserver) {
  47907. this.onDisposeObservable.remove(this._onDisposeObserver);
  47908. }
  47909. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  47910. },
  47911. enumerable: true,
  47912. configurable: true
  47913. });
  47914. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  47915. /**
  47916. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  47917. */
  47918. get: function () {
  47919. return this._isAnimationSheetEnabled;
  47920. },
  47921. enumerable: true,
  47922. configurable: true
  47923. });
  47924. ParticleSystem.prototype._createIndexBuffer = function () {
  47925. var indices = [];
  47926. var index = 0;
  47927. for (var count = 0; count < this._capacity; count++) {
  47928. indices.push(index);
  47929. indices.push(index + 1);
  47930. indices.push(index + 2);
  47931. indices.push(index);
  47932. indices.push(index + 2);
  47933. indices.push(index + 3);
  47934. index += 4;
  47935. }
  47936. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  47937. };
  47938. /**
  47939. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  47940. * Its lifetime will start back at 0.
  47941. * @param particle The particle to recycle
  47942. */
  47943. ParticleSystem.prototype.recycleParticle = function (particle) {
  47944. var lastParticle = this._particles.pop();
  47945. if (lastParticle !== particle) {
  47946. lastParticle.copyTo(particle);
  47947. this._stockParticles.push(lastParticle);
  47948. }
  47949. };
  47950. /**
  47951. * Gets the maximum number of particles active at the same time.
  47952. * @returns The max number of active particles.
  47953. */
  47954. ParticleSystem.prototype.getCapacity = function () {
  47955. return this._capacity;
  47956. };
  47957. /**
  47958. * Gets Wether there are still active particles in the system.
  47959. * @returns True if it is alive, otherwise false.
  47960. */
  47961. ParticleSystem.prototype.isAlive = function () {
  47962. return this._alive;
  47963. };
  47964. /**
  47965. * Gets Wether the system has been started.
  47966. * @returns True if it has been started, otherwise false.
  47967. */
  47968. ParticleSystem.prototype.isStarted = function () {
  47969. return this._started;
  47970. };
  47971. /**
  47972. * Starts the particle system and begins to emit.
  47973. */
  47974. ParticleSystem.prototype.start = function () {
  47975. this._started = true;
  47976. this._stopped = false;
  47977. this._actualFrame = 0;
  47978. };
  47979. /**
  47980. * Stops the particle system.
  47981. */
  47982. ParticleSystem.prototype.stop = function () {
  47983. this._stopped = true;
  47984. };
  47985. /**
  47986. * @ignore (for internal use only)
  47987. */
  47988. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  47989. var offset = index * this._vertexBufferSize;
  47990. this._vertexData[offset] = particle.position.x;
  47991. this._vertexData[offset + 1] = particle.position.y;
  47992. this._vertexData[offset + 2] = particle.position.z;
  47993. this._vertexData[offset + 3] = particle.color.r;
  47994. this._vertexData[offset + 4] = particle.color.g;
  47995. this._vertexData[offset + 5] = particle.color.b;
  47996. this._vertexData[offset + 6] = particle.color.a;
  47997. this._vertexData[offset + 7] = particle.angle;
  47998. this._vertexData[offset + 8] = particle.size;
  47999. this._vertexData[offset + 9] = offsetX;
  48000. this._vertexData[offset + 10] = offsetY;
  48001. };
  48002. /**
  48003. * @ignore (for internal use only)
  48004. */
  48005. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  48006. if (offsetX === 0)
  48007. offsetX = this._epsilon;
  48008. else if (offsetX === 1)
  48009. offsetX = 1 - this._epsilon;
  48010. if (offsetY === 0)
  48011. offsetY = this._epsilon;
  48012. else if (offsetY === 1)
  48013. offsetY = 1 - this._epsilon;
  48014. var offset = index * this._vertexBufferSize;
  48015. this._vertexData[offset] = particle.position.x;
  48016. this._vertexData[offset + 1] = particle.position.y;
  48017. this._vertexData[offset + 2] = particle.position.z;
  48018. this._vertexData[offset + 3] = particle.color.r;
  48019. this._vertexData[offset + 4] = particle.color.g;
  48020. this._vertexData[offset + 5] = particle.color.b;
  48021. this._vertexData[offset + 6] = particle.color.a;
  48022. this._vertexData[offset + 7] = particle.angle;
  48023. this._vertexData[offset + 8] = particle.size;
  48024. this._vertexData[offset + 9] = offsetX;
  48025. this._vertexData[offset + 10] = offsetY;
  48026. this._vertexData[offset + 11] = particle.cellIndex;
  48027. };
  48028. ParticleSystem.prototype._update = function (newParticles) {
  48029. // Update current
  48030. this._alive = this._particles.length > 0;
  48031. this.updateFunction(this._particles);
  48032. // Add new ones
  48033. var worldMatrix;
  48034. if (this.emitter.position) {
  48035. var emitterMesh = this.emitter;
  48036. worldMatrix = emitterMesh.getWorldMatrix();
  48037. }
  48038. else {
  48039. var emitterPosition = this.emitter;
  48040. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  48041. }
  48042. var particle;
  48043. for (var index = 0; index < newParticles; index++) {
  48044. if (this._particles.length === this._capacity) {
  48045. break;
  48046. }
  48047. if (this._stockParticles.length !== 0) {
  48048. particle = this._stockParticles.pop();
  48049. particle.age = 0;
  48050. particle.cellIndex = this.startSpriteCellID;
  48051. }
  48052. else {
  48053. particle = new BABYLON.Particle(this);
  48054. }
  48055. this._particles.push(particle);
  48056. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  48057. if (this.startPositionFunction) {
  48058. this.startPositionFunction(worldMatrix, particle.position, particle);
  48059. }
  48060. else {
  48061. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  48062. }
  48063. if (this.startDirectionFunction) {
  48064. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  48065. }
  48066. else {
  48067. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  48068. }
  48069. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  48070. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  48071. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  48072. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  48073. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  48074. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  48075. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  48076. }
  48077. };
  48078. ParticleSystem.prototype._getEffect = function () {
  48079. if (this._customEffect) {
  48080. return this._customEffect;
  48081. }
  48082. ;
  48083. var defines = [];
  48084. if (this._scene.clipPlane) {
  48085. defines.push("#define CLIPPLANE");
  48086. }
  48087. if (this._isAnimationSheetEnabled) {
  48088. defines.push("#define ANIMATESHEET");
  48089. }
  48090. // Effect
  48091. var join = defines.join("\n");
  48092. if (this._cachedDefines !== join) {
  48093. this._cachedDefines = join;
  48094. var attributesNamesOrOptions;
  48095. var effectCreationOption;
  48096. if (this._isAnimationSheetEnabled) {
  48097. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  48098. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  48099. }
  48100. else {
  48101. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  48102. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  48103. }
  48104. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  48105. }
  48106. return this._effect;
  48107. };
  48108. /**
  48109. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  48110. */
  48111. ParticleSystem.prototype.animate = function () {
  48112. if (!this._started)
  48113. return;
  48114. var effect = this._getEffect();
  48115. // Check
  48116. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  48117. return;
  48118. if (this._currentRenderId === this._scene.getRenderId()) {
  48119. return;
  48120. }
  48121. this._currentRenderId = this._scene.getRenderId();
  48122. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  48123. // determine the number of particles we need to create
  48124. var newParticles;
  48125. if (this.manualEmitCount > -1) {
  48126. newParticles = this.manualEmitCount;
  48127. this._newPartsExcess = 0;
  48128. this.manualEmitCount = 0;
  48129. }
  48130. else {
  48131. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  48132. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  48133. }
  48134. if (this._newPartsExcess > 1.0) {
  48135. newParticles += this._newPartsExcess >> 0;
  48136. this._newPartsExcess -= this._newPartsExcess >> 0;
  48137. }
  48138. this._alive = false;
  48139. if (!this._stopped) {
  48140. this._actualFrame += this._scaledUpdateSpeed;
  48141. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  48142. this.stop();
  48143. }
  48144. else {
  48145. newParticles = 0;
  48146. }
  48147. this._update(newParticles);
  48148. // Stopped?
  48149. if (this._stopped) {
  48150. if (!this._alive) {
  48151. this._started = false;
  48152. if (this.onAnimationEnd) {
  48153. this.onAnimationEnd();
  48154. }
  48155. if (this.disposeOnStop) {
  48156. this._scene._toBeDisposed.push(this);
  48157. }
  48158. }
  48159. }
  48160. // Animation sheet
  48161. if (this._isAnimationSheetEnabled) {
  48162. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  48163. }
  48164. else {
  48165. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  48166. }
  48167. // Update VBO
  48168. var offset = 0;
  48169. for (var index = 0; index < this._particles.length; index++) {
  48170. var particle = this._particles[index];
  48171. this._appendParticleVertexes(offset, particle);
  48172. offset += 4;
  48173. }
  48174. if (this._vertexBuffer) {
  48175. this._vertexBuffer.update(this._vertexData);
  48176. }
  48177. };
  48178. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  48179. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  48180. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  48181. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  48182. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  48183. };
  48184. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  48185. this._appendParticleVertex(offset++, particle, 0, 0);
  48186. this._appendParticleVertex(offset++, particle, 1, 0);
  48187. this._appendParticleVertex(offset++, particle, 1, 1);
  48188. this._appendParticleVertex(offset++, particle, 0, 1);
  48189. };
  48190. /**
  48191. * Rebuilds the particle system.
  48192. */
  48193. ParticleSystem.prototype.rebuild = function () {
  48194. this._createIndexBuffer();
  48195. if (this._vertexBuffer) {
  48196. this._vertexBuffer._rebuild();
  48197. }
  48198. };
  48199. /**
  48200. * Renders the particle system in its current state.
  48201. * @returns the current number of particles.
  48202. */
  48203. ParticleSystem.prototype.render = function () {
  48204. var effect = this._getEffect();
  48205. // Check
  48206. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this._particles.length)
  48207. return 0;
  48208. var engine = this._scene.getEngine();
  48209. // Render
  48210. engine.enableEffect(effect);
  48211. engine.setState(false);
  48212. var viewMatrix = this._scene.getViewMatrix();
  48213. effect.setTexture("diffuseSampler", this.particleTexture);
  48214. effect.setMatrix("view", viewMatrix);
  48215. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  48216. if (this._isAnimationSheetEnabled) {
  48217. var baseSize = this.particleTexture.getBaseSize();
  48218. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  48219. }
  48220. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  48221. if (this._scene.clipPlane) {
  48222. var clipPlane = this._scene.clipPlane;
  48223. var invView = viewMatrix.clone();
  48224. invView.invert();
  48225. effect.setMatrix("invView", invView);
  48226. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  48227. }
  48228. // VBOs
  48229. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  48230. // Draw order
  48231. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  48232. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  48233. }
  48234. else {
  48235. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  48236. }
  48237. if (this.forceDepthWrite) {
  48238. engine.setDepthWrite(true);
  48239. }
  48240. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  48241. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  48242. return this._particles.length;
  48243. };
  48244. /**
  48245. * Disposes the particle system and free the associated resources.
  48246. */
  48247. ParticleSystem.prototype.dispose = function () {
  48248. if (this._vertexBuffer) {
  48249. this._vertexBuffer.dispose();
  48250. this._vertexBuffer = null;
  48251. }
  48252. if (this._indexBuffer) {
  48253. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  48254. this._indexBuffer = null;
  48255. }
  48256. if (this.particleTexture) {
  48257. this.particleTexture.dispose();
  48258. this.particleTexture = null;
  48259. }
  48260. // Remove from scene
  48261. var index = this._scene.particleSystems.indexOf(this);
  48262. if (index > -1) {
  48263. this._scene.particleSystems.splice(index, 1);
  48264. }
  48265. // Callback
  48266. this.onDisposeObservable.notifyObservers(this);
  48267. this.onDisposeObservable.clear();
  48268. };
  48269. /**
  48270. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  48271. * @param radius The radius of the sphere to emit from
  48272. * @returns the emitter
  48273. */
  48274. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  48275. if (radius === void 0) { radius = 1; }
  48276. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  48277. this.particleEmitterType = particleEmitter;
  48278. return particleEmitter;
  48279. };
  48280. /**
  48281. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  48282. * @param radius The radius of the sphere to emit from
  48283. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  48284. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  48285. * @returns the emitter
  48286. */
  48287. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  48288. if (radius === void 0) { radius = 1; }
  48289. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  48290. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  48291. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  48292. this.particleEmitterType = particleEmitter;
  48293. return particleEmitter;
  48294. };
  48295. /**
  48296. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  48297. * @param radius The radius of the cone to emit from
  48298. * @param angle The base angle of the cone
  48299. * @returns the emitter
  48300. */
  48301. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  48302. if (radius === void 0) { radius = 1; }
  48303. if (angle === void 0) { angle = Math.PI / 4; }
  48304. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  48305. this.particleEmitterType = particleEmitter;
  48306. return particleEmitter;
  48307. };
  48308. // this method needs to be changed when breaking changes will be allowed to match the sphere and cone methods and properties direction1,2 and minEmitBox,maxEmitBox to be removed from the system.
  48309. /**
  48310. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  48311. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  48312. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  48313. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  48314. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  48315. * @returns the emitter
  48316. */
  48317. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  48318. var particleEmitter = new BABYLON.BoxParticleEmitter(this);
  48319. this.direction1 = direction1;
  48320. this.direction2 = direction2;
  48321. this.minEmitBox = minEmitBox;
  48322. this.maxEmitBox = maxEmitBox;
  48323. this.particleEmitterType = particleEmitter;
  48324. return particleEmitter;
  48325. };
  48326. /**
  48327. * Clones the particle system.
  48328. * @param name The name of the cloned object
  48329. * @param newEmitter The new emitter to use
  48330. * @returns the cloned particle system
  48331. */
  48332. ParticleSystem.prototype.clone = function (name, newEmitter) {
  48333. var custom = null;
  48334. var program = null;
  48335. if (this.customShader != null) {
  48336. program = this.customShader;
  48337. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  48338. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  48339. }
  48340. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  48341. result.customShader = program;
  48342. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  48343. if (newEmitter === undefined) {
  48344. newEmitter = this.emitter;
  48345. }
  48346. result.emitter = newEmitter;
  48347. if (this.particleTexture) {
  48348. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  48349. }
  48350. if (!this.preventAutoStart) {
  48351. result.start();
  48352. }
  48353. return result;
  48354. };
  48355. /**
  48356. * Serializes the particle system to a JSON object.
  48357. * @returns the JSON object
  48358. */
  48359. ParticleSystem.prototype.serialize = function () {
  48360. var serializationObject = {};
  48361. serializationObject.name = this.name;
  48362. serializationObject.id = this.id;
  48363. // Emitter
  48364. if (this.emitter.position) {
  48365. var emitterMesh = this.emitter;
  48366. serializationObject.emitterId = emitterMesh.id;
  48367. }
  48368. else {
  48369. var emitterPosition = this.emitter;
  48370. serializationObject.emitter = emitterPosition.asArray();
  48371. }
  48372. serializationObject.capacity = this.getCapacity();
  48373. if (this.particleTexture) {
  48374. serializationObject.textureName = this.particleTexture.name;
  48375. }
  48376. // Animations
  48377. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  48378. // Particle system
  48379. serializationObject.minAngularSpeed = this.minAngularSpeed;
  48380. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  48381. serializationObject.minSize = this.minSize;
  48382. serializationObject.maxSize = this.maxSize;
  48383. serializationObject.minEmitPower = this.minEmitPower;
  48384. serializationObject.maxEmitPower = this.maxEmitPower;
  48385. serializationObject.minLifeTime = this.minLifeTime;
  48386. serializationObject.maxLifeTime = this.maxLifeTime;
  48387. serializationObject.emitRate = this.emitRate;
  48388. serializationObject.minEmitBox = this.minEmitBox.asArray();
  48389. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  48390. serializationObject.gravity = this.gravity.asArray();
  48391. serializationObject.direction1 = this.direction1.asArray();
  48392. serializationObject.direction2 = this.direction2.asArray();
  48393. serializationObject.color1 = this.color1.asArray();
  48394. serializationObject.color2 = this.color2.asArray();
  48395. serializationObject.colorDead = this.colorDead.asArray();
  48396. serializationObject.updateSpeed = this.updateSpeed;
  48397. serializationObject.targetStopDuration = this.targetStopDuration;
  48398. serializationObject.textureMask = this.textureMask.asArray();
  48399. serializationObject.blendMode = this.blendMode;
  48400. serializationObject.customShader = this.customShader;
  48401. serializationObject.preventAutoStart = this.preventAutoStart;
  48402. serializationObject.startSpriteCellID = this.startSpriteCellID;
  48403. serializationObject.endSpriteCellID = this.endSpriteCellID;
  48404. serializationObject.spriteCellLoop = this.spriteCellLoop;
  48405. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  48406. serializationObject.spriteCellWidth = this.spriteCellWidth;
  48407. serializationObject.spriteCellHeight = this.spriteCellHeight;
  48408. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  48409. return serializationObject;
  48410. };
  48411. /**
  48412. * Parses a JSON object to create a particle system.
  48413. * @param parsedParticleSystem The JSON object to parse
  48414. * @param scene The scene to create the particle system in
  48415. * @param rootUrl The root url to use to load external dependencies like texture
  48416. * @returns the Parsed particle system
  48417. */
  48418. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  48419. var name = parsedParticleSystem.name;
  48420. var custom = null;
  48421. var program = null;
  48422. if (parsedParticleSystem.customShader) {
  48423. program = parsedParticleSystem.customShader;
  48424. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  48425. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  48426. }
  48427. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  48428. particleSystem.customShader = program;
  48429. if (parsedParticleSystem.id) {
  48430. particleSystem.id = parsedParticleSystem.id;
  48431. }
  48432. // Auto start
  48433. if (parsedParticleSystem.preventAutoStart) {
  48434. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  48435. }
  48436. // Texture
  48437. if (parsedParticleSystem.textureName) {
  48438. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  48439. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  48440. }
  48441. // Emitter
  48442. if (parsedParticleSystem.emitterId) {
  48443. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  48444. }
  48445. else {
  48446. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  48447. }
  48448. // Animations
  48449. if (parsedParticleSystem.animations) {
  48450. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  48451. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  48452. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  48453. }
  48454. }
  48455. if (parsedParticleSystem.autoAnimate) {
  48456. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  48457. }
  48458. // Particle system
  48459. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  48460. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  48461. particleSystem.minSize = parsedParticleSystem.minSize;
  48462. particleSystem.maxSize = parsedParticleSystem.maxSize;
  48463. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  48464. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  48465. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  48466. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  48467. particleSystem.emitRate = parsedParticleSystem.emitRate;
  48468. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  48469. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  48470. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  48471. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  48472. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  48473. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  48474. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  48475. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  48476. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  48477. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  48478. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  48479. particleSystem.blendMode = parsedParticleSystem.blendMode;
  48480. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  48481. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  48482. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  48483. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  48484. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  48485. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  48486. if (!particleSystem.preventAutoStart) {
  48487. particleSystem.start();
  48488. }
  48489. return particleSystem;
  48490. };
  48491. /**
  48492. * Source color is added to the destination color without alpha affecting the result.
  48493. */
  48494. ParticleSystem.BLENDMODE_ONEONE = 0;
  48495. /**
  48496. * Blend current color and particle color using particle’s alpha.
  48497. */
  48498. ParticleSystem.BLENDMODE_STANDARD = 1;
  48499. return ParticleSystem;
  48500. }());
  48501. BABYLON.ParticleSystem = ParticleSystem;
  48502. })(BABYLON || (BABYLON = {}));
  48503. //# sourceMappingURL=babylon.particleSystem.js.map
  48504. var BABYLON;
  48505. (function (BABYLON) {
  48506. /**
  48507. * Particle emitter emitting particles from the inside of a box.
  48508. * It emits the particles randomly between 2 given directions.
  48509. */
  48510. var BoxParticleEmitter = /** @class */ (function () {
  48511. // to be updated like the rest of emitters when breaking changes.
  48512. // all property should be come public variables and passed through constructor.
  48513. /**
  48514. * Creates a new instance of @see BoxParticleEmitter
  48515. * @param _particleSystem the particle system associated with the emitter
  48516. */
  48517. function BoxParticleEmitter(_particleSystem) {
  48518. this._particleSystem = _particleSystem;
  48519. }
  48520. Object.defineProperty(BoxParticleEmitter.prototype, "direction1", {
  48521. /**
  48522. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  48523. */
  48524. get: function () {
  48525. return this._particleSystem.direction1;
  48526. },
  48527. /**
  48528. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  48529. */
  48530. set: function (value) {
  48531. this._particleSystem.direction1 = value;
  48532. },
  48533. enumerable: true,
  48534. configurable: true
  48535. });
  48536. Object.defineProperty(BoxParticleEmitter.prototype, "direction2", {
  48537. /**
  48538. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  48539. */
  48540. get: function () {
  48541. return this._particleSystem.direction2;
  48542. },
  48543. /**
  48544. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  48545. */
  48546. set: function (value) {
  48547. this._particleSystem.direction2 = value;
  48548. },
  48549. enumerable: true,
  48550. configurable: true
  48551. });
  48552. Object.defineProperty(BoxParticleEmitter.prototype, "minEmitBox", {
  48553. /**
  48554. * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  48555. */
  48556. get: function () {
  48557. return this._particleSystem.minEmitBox;
  48558. },
  48559. /**
  48560. * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  48561. */
  48562. set: function (value) {
  48563. this._particleSystem.minEmitBox = value;
  48564. },
  48565. enumerable: true,
  48566. configurable: true
  48567. });
  48568. Object.defineProperty(BoxParticleEmitter.prototype, "maxEmitBox", {
  48569. /**
  48570. * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  48571. */
  48572. get: function () {
  48573. return this._particleSystem.maxEmitBox;
  48574. },
  48575. /**
  48576. * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  48577. */
  48578. set: function (value) {
  48579. this._particleSystem.maxEmitBox = value;
  48580. },
  48581. enumerable: true,
  48582. configurable: true
  48583. });
  48584. /**
  48585. * Called by the particle System when the direction is computed for the created particle.
  48586. * @param emitPower is the power of the particle (speed)
  48587. * @param worldMatrix is the world matrix of the particle system
  48588. * @param directionToUpdate is the direction vector to update with the result
  48589. * @param particle is the particle we are computed the direction for
  48590. */
  48591. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  48592. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  48593. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  48594. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  48595. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  48596. };
  48597. /**
  48598. * Called by the particle System when the position is computed for the created particle.
  48599. * @param worldMatrix is the world matrix of the particle system
  48600. * @param positionToUpdate is the position vector to update with the result
  48601. * @param particle is the particle we are computed the position for
  48602. */
  48603. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  48604. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  48605. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  48606. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  48607. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  48608. };
  48609. /**
  48610. * Clones the current emitter and returns a copy of it
  48611. * @returns the new emitter
  48612. */
  48613. BoxParticleEmitter.prototype.clone = function () {
  48614. var newOne = new BoxParticleEmitter(this._particleSystem);
  48615. BABYLON.Tools.DeepCopy(this, newOne);
  48616. return newOne;
  48617. };
  48618. return BoxParticleEmitter;
  48619. }());
  48620. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  48621. })(BABYLON || (BABYLON = {}));
  48622. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  48623. var BABYLON;
  48624. (function (BABYLON) {
  48625. /**
  48626. * Particle emitter emitting particles from the inside of a cone.
  48627. * It emits the particles alongside the cone volume from the base to the particle.
  48628. * The emission direction might be randomized.
  48629. */
  48630. var ConeParticleEmitter = /** @class */ (function () {
  48631. /**
  48632. * Creates a new instance of @see ConeParticleEmitter
  48633. * @param radius the radius of the emission cone
  48634. * @param angles the cone base angle
  48635. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  48636. */
  48637. function ConeParticleEmitter(radius,
  48638. /**
  48639. * The radius of the emission cone.
  48640. */
  48641. angle,
  48642. /**
  48643. * The cone base angle.
  48644. */
  48645. directionRandomizer) {
  48646. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  48647. this.angle = angle;
  48648. this.directionRandomizer = directionRandomizer;
  48649. this.radius = radius;
  48650. }
  48651. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  48652. /**
  48653. * Gets the radius of the emission cone.
  48654. */
  48655. get: function () {
  48656. return this._radius;
  48657. },
  48658. /**
  48659. * Sets the radius of the emission cone.
  48660. */
  48661. set: function (value) {
  48662. this._radius = value;
  48663. if (this.angle !== 0) {
  48664. this._height = value / Math.tan(this.angle / 2);
  48665. }
  48666. else {
  48667. this._height = 1;
  48668. }
  48669. },
  48670. enumerable: true,
  48671. configurable: true
  48672. });
  48673. /**
  48674. * Called by the particle System when the direction is computed for the created particle.
  48675. * @param emitPower is the power of the particle (speed)
  48676. * @param worldMatrix is the world matrix of the particle system
  48677. * @param directionToUpdate is the direction vector to update with the result
  48678. * @param particle is the particle we are computed the direction for
  48679. */
  48680. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  48681. if (this.angle === 0) {
  48682. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  48683. }
  48684. else {
  48685. // measure the direction Vector from the emitter to the particle.
  48686. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  48687. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  48688. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  48689. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  48690. direction.x += randX;
  48691. direction.y += randY;
  48692. direction.z += randZ;
  48693. direction.normalize();
  48694. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  48695. }
  48696. };
  48697. /**
  48698. * Called by the particle System when the position is computed for the created particle.
  48699. * @param worldMatrix is the world matrix of the particle system
  48700. * @param positionToUpdate is the position vector to update with the result
  48701. * @param particle is the particle we are computed the position for
  48702. */
  48703. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  48704. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  48705. var h = BABYLON.Scalar.RandomRange(0, 1);
  48706. // Better distribution in a cone at normal angles.
  48707. h = 1 - h * h;
  48708. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  48709. radius = radius * h / this._height;
  48710. var randX = radius * Math.sin(s);
  48711. var randZ = radius * Math.cos(s);
  48712. var randY = h;
  48713. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  48714. };
  48715. /**
  48716. * Clones the current emitter and returns a copy of it
  48717. * @returns the new emitter
  48718. */
  48719. ConeParticleEmitter.prototype.clone = function () {
  48720. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  48721. BABYLON.Tools.DeepCopy(this, newOne);
  48722. return newOne;
  48723. };
  48724. return ConeParticleEmitter;
  48725. }());
  48726. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  48727. })(BABYLON || (BABYLON = {}));
  48728. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  48729. var BABYLON;
  48730. (function (BABYLON) {
  48731. /**
  48732. * Particle emitter emitting particles from the inside of a sphere.
  48733. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  48734. */
  48735. var SphereParticleEmitter = /** @class */ (function () {
  48736. /**
  48737. * Creates a new instance of @see SphereParticleEmitter
  48738. * @param radius the radius of the emission sphere
  48739. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  48740. */
  48741. function SphereParticleEmitter(
  48742. /**
  48743. * The radius of the emission sphere.
  48744. */
  48745. radius,
  48746. /**
  48747. * How much to randomize the particle direction [0-1].
  48748. */
  48749. directionRandomizer) {
  48750. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  48751. this.radius = radius;
  48752. this.directionRandomizer = directionRandomizer;
  48753. }
  48754. /**
  48755. * Called by the particle System when the direction is computed for the created particle.
  48756. * @param emitPower is the power of the particle (speed)
  48757. * @param worldMatrix is the world matrix of the particle system
  48758. * @param directionToUpdate is the direction vector to update with the result
  48759. * @param particle is the particle we are computed the direction for
  48760. */
  48761. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  48762. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  48763. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  48764. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  48765. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  48766. direction.x += randX;
  48767. direction.y += randY;
  48768. direction.z += randZ;
  48769. direction.normalize();
  48770. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  48771. };
  48772. /**
  48773. * Called by the particle System when the position is computed for the created particle.
  48774. * @param worldMatrix is the world matrix of the particle system
  48775. * @param positionToUpdate is the position vector to update with the result
  48776. * @param particle is the particle we are computed the position for
  48777. */
  48778. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  48779. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  48780. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  48781. var randX = this.radius * Math.cos(phi) * Math.sin(theta);
  48782. var randY = this.radius * Math.cos(theta);
  48783. var randZ = this.radius * Math.sin(phi) * Math.sin(theta);
  48784. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  48785. };
  48786. /**
  48787. * Clones the current emitter and returns a copy of it
  48788. * @returns the new emitter
  48789. */
  48790. SphereParticleEmitter.prototype.clone = function () {
  48791. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  48792. BABYLON.Tools.DeepCopy(this, newOne);
  48793. return newOne;
  48794. };
  48795. return SphereParticleEmitter;
  48796. }());
  48797. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  48798. /**
  48799. * Particle emitter emitting particles from the inside of a sphere.
  48800. * It emits the particles randomly between two vectors.
  48801. */
  48802. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  48803. __extends(SphereDirectedParticleEmitter, _super);
  48804. /**
  48805. * Creates a new instance of @see SphereDirectedParticleEmitter
  48806. * @param radius the radius of the emission sphere
  48807. * @param direction1 the min limit of the emission direction
  48808. * @param direction2 the max limit of the emission direction
  48809. */
  48810. function SphereDirectedParticleEmitter(radius,
  48811. /**
  48812. * The min limit of the emission direction.
  48813. */
  48814. direction1,
  48815. /**
  48816. * The max limit of the emission direction.
  48817. */
  48818. direction2) {
  48819. var _this = _super.call(this, radius) || this;
  48820. _this.direction1 = direction1;
  48821. _this.direction2 = direction2;
  48822. return _this;
  48823. }
  48824. /**
  48825. * Called by the particle System when the direction is computed for the created particle.
  48826. * @param emitPower is the power of the particle (speed)
  48827. * @param worldMatrix is the world matrix of the particle system
  48828. * @param directionToUpdate is the direction vector to update with the result
  48829. * @param particle is the particle we are computed the direction for
  48830. */
  48831. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  48832. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  48833. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  48834. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  48835. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  48836. };
  48837. /**
  48838. * Clones the current emitter and returns a copy of it
  48839. * @returns the new emitter
  48840. */
  48841. SphereDirectedParticleEmitter.prototype.clone = function () {
  48842. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  48843. BABYLON.Tools.DeepCopy(this, newOne);
  48844. return newOne;
  48845. };
  48846. return SphereDirectedParticleEmitter;
  48847. }(SphereParticleEmitter));
  48848. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  48849. })(BABYLON || (BABYLON = {}));
  48850. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  48851. //# sourceMappingURL=babylon.iParticleEmitterType.js.map
  48852. var BABYLON;
  48853. (function (BABYLON) {
  48854. /**
  48855. * Represents one particle of a solid particle system.
  48856. * @see SolidParticleSystem
  48857. */
  48858. var SolidParticle = /** @class */ (function () {
  48859. /**
  48860. * Creates a Solid Particle object.
  48861. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  48862. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  48863. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  48864. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  48865. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  48866. * @param shapeId (integer) is the model shape identifier in the SPS.
  48867. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  48868. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  48869. */
  48870. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  48871. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  48872. /**
  48873. * particle global index
  48874. */
  48875. this.idx = 0;
  48876. /**
  48877. * The color of the particle
  48878. */
  48879. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  48880. /**
  48881. * The world space position of the particle.
  48882. */
  48883. this.position = BABYLON.Vector3.Zero();
  48884. /**
  48885. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  48886. */
  48887. this.rotation = BABYLON.Vector3.Zero();
  48888. /**
  48889. * The scaling of the particle.
  48890. */
  48891. this.scaling = BABYLON.Vector3.One();
  48892. /**
  48893. * The uvs of the particle.
  48894. */
  48895. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  48896. /**
  48897. * The current speed of the particle.
  48898. */
  48899. this.velocity = BABYLON.Vector3.Zero();
  48900. /**
  48901. * The pivot point in the particle local space.
  48902. */
  48903. this.pivot = BABYLON.Vector3.Zero();
  48904. /**
  48905. * Is the particle active or not ?
  48906. */
  48907. this.alive = true;
  48908. /**
  48909. * Is the particle visible or not ?
  48910. */
  48911. this.isVisible = true;
  48912. /**
  48913. * Index of this particle in the global "positions" array (Internal use)
  48914. */
  48915. this._pos = 0;
  48916. /**
  48917. * Index of this particle in the global "indices" array (Internal use)
  48918. */
  48919. this._ind = 0;
  48920. /**
  48921. * ModelShape id of this particle
  48922. */
  48923. this.shapeId = 0;
  48924. /**
  48925. * Index of the particle in its shape id (Internal use)
  48926. */
  48927. this.idxInShape = 0;
  48928. /**
  48929. * Still set as invisible in order to skip useless computations (Internal use)
  48930. */
  48931. this._stillInvisible = false;
  48932. this.idx = particleIndex;
  48933. this._pos = positionIndex;
  48934. this._ind = indiceIndex;
  48935. this._model = model;
  48936. this.shapeId = shapeId;
  48937. this.idxInShape = idxInShape;
  48938. this._sps = sps;
  48939. if (modelBoundingInfo) {
  48940. this._modelBoundingInfo = modelBoundingInfo;
  48941. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  48942. }
  48943. }
  48944. Object.defineProperty(SolidParticle.prototype, "scale", {
  48945. /**
  48946. * Legacy support, changed scale to scaling
  48947. */
  48948. get: function () {
  48949. return this.scaling;
  48950. },
  48951. /**
  48952. * Legacy support, changed scale to scaling
  48953. */
  48954. set: function (scale) {
  48955. this.scaling = scale;
  48956. },
  48957. enumerable: true,
  48958. configurable: true
  48959. });
  48960. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  48961. /**
  48962. * Legacy support, changed quaternion to rotationQuaternion
  48963. */
  48964. get: function () {
  48965. return this.rotationQuaternion;
  48966. },
  48967. /**
  48968. * Legacy support, changed quaternion to rotationQuaternion
  48969. */
  48970. set: function (q) {
  48971. this.rotationQuaternion = q;
  48972. },
  48973. enumerable: true,
  48974. configurable: true
  48975. });
  48976. /**
  48977. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  48978. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  48979. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  48980. * @returns true if it intersects
  48981. */
  48982. SolidParticle.prototype.intersectsMesh = function (target) {
  48983. if (!this._boundingInfo || !target._boundingInfo) {
  48984. return false;
  48985. }
  48986. if (this._sps._bSphereOnly) {
  48987. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  48988. }
  48989. return this._boundingInfo.intersects(target._boundingInfo, false);
  48990. };
  48991. return SolidParticle;
  48992. }());
  48993. BABYLON.SolidParticle = SolidParticle;
  48994. /**
  48995. * Represents the shape of the model used by one particle of a solid particle system.
  48996. * SPS internal tool, don't use it manually.
  48997. * @see SolidParticleSystem
  48998. */
  48999. var ModelShape = /** @class */ (function () {
  49000. /**
  49001. * 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.
  49002. * SPS internal tool, don't use it manually.
  49003. * @ignore
  49004. */
  49005. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  49006. /**
  49007. * length of the shape in the model indices array (internal use)
  49008. */
  49009. this._indicesLength = 0;
  49010. this.shapeID = id;
  49011. this._shape = shape;
  49012. this._indicesLength = indicesLength;
  49013. this._shapeUV = shapeUV;
  49014. this._positionFunction = posFunction;
  49015. this._vertexFunction = vtxFunction;
  49016. }
  49017. return ModelShape;
  49018. }());
  49019. BABYLON.ModelShape = ModelShape;
  49020. /**
  49021. * Represents a Depth Sorted Particle in the solid particle system.
  49022. * @see SolidParticleSystem
  49023. */
  49024. var DepthSortedParticle = /** @class */ (function () {
  49025. function DepthSortedParticle() {
  49026. /**
  49027. * Index of the particle in the "indices" array
  49028. */
  49029. this.ind = 0;
  49030. /**
  49031. * Length of the particle shape in the "indices" array
  49032. */
  49033. this.indicesLength = 0;
  49034. /**
  49035. * Squared distance from the particle to the camera
  49036. */
  49037. this.sqDistance = 0.0;
  49038. }
  49039. return DepthSortedParticle;
  49040. }());
  49041. BABYLON.DepthSortedParticle = DepthSortedParticle;
  49042. })(BABYLON || (BABYLON = {}));
  49043. //# sourceMappingURL=babylon.solidParticle.js.map
  49044. var BABYLON;
  49045. (function (BABYLON) {
  49046. /**
  49047. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  49048. *As it is just a mesh, the SPS has all the same properties than any other BJS mesh : not more, not less. It can be scaled, rotated, translated, enlighted, textured, moved, etc.
  49049. * The SPS is also a particle system. It provides some methods to manage the particles.
  49050. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  49051. *
  49052. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  49053. */
  49054. var SolidParticleSystem = /** @class */ (function () {
  49055. /**
  49056. * Creates a SPS (Solid Particle System) object.
  49057. * @param name (String) is the SPS name, this will be the underlying mesh name.
  49058. * @param scene (Scene) is the scene in which the SPS is added.
  49059. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  49060. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  49061. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  49062. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  49063. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  49064. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  49065. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  49066. */
  49067. function SolidParticleSystem(name, scene, options) {
  49068. /**
  49069. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  49070. * Example : var p = SPS.particles[i];
  49071. */
  49072. this.particles = new Array();
  49073. /**
  49074. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  49075. */
  49076. this.nbParticles = 0;
  49077. /**
  49078. * If the particles must ever face the camera (default false). Useful for planar particles.
  49079. */
  49080. this.billboard = false;
  49081. /**
  49082. * Recompute normals when adding a shape
  49083. */
  49084. this.recomputeNormals = true;
  49085. /**
  49086. * This a counter ofr your own usage. It's not set by any SPS functions.
  49087. */
  49088. this.counter = 0;
  49089. /**
  49090. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  49091. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  49092. */
  49093. this.vars = {};
  49094. /**
  49095. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  49096. */
  49097. this._bSphereOnly = false;
  49098. /**
  49099. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  49100. */
  49101. this._bSphereRadiusFactor = 1.0;
  49102. this._positions = new Array();
  49103. this._indices = new Array();
  49104. this._normals = new Array();
  49105. this._colors = new Array();
  49106. this._uvs = new Array();
  49107. this._index = 0; // indices index
  49108. this._updatable = true;
  49109. this._pickable = false;
  49110. this._isVisibilityBoxLocked = false;
  49111. this._alwaysVisible = false;
  49112. this._depthSort = false;
  49113. this._shapeCounter = 0;
  49114. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  49115. this._color = new BABYLON.Color4(0, 0, 0, 0);
  49116. this._computeParticleColor = true;
  49117. this._computeParticleTexture = true;
  49118. this._computeParticleRotation = true;
  49119. this._computeParticleVertex = false;
  49120. this._computeBoundingBox = false;
  49121. this._depthSortParticles = true;
  49122. this._cam_axisZ = BABYLON.Vector3.Zero();
  49123. this._cam_axisY = BABYLON.Vector3.Zero();
  49124. this._cam_axisX = BABYLON.Vector3.Zero();
  49125. this._axisZ = BABYLON.Axis.Z;
  49126. this._camDir = BABYLON.Vector3.Zero();
  49127. this._camInvertedPosition = BABYLON.Vector3.Zero();
  49128. this._rotMatrix = new BABYLON.Matrix();
  49129. this._invertMatrix = new BABYLON.Matrix();
  49130. this._rotated = BABYLON.Vector3.Zero();
  49131. this._quaternion = new BABYLON.Quaternion();
  49132. this._vertex = BABYLON.Vector3.Zero();
  49133. this._normal = BABYLON.Vector3.Zero();
  49134. this._yaw = 0.0;
  49135. this._pitch = 0.0;
  49136. this._roll = 0.0;
  49137. this._halfroll = 0.0;
  49138. this._halfpitch = 0.0;
  49139. this._halfyaw = 0.0;
  49140. this._sinRoll = 0.0;
  49141. this._cosRoll = 0.0;
  49142. this._sinPitch = 0.0;
  49143. this._cosPitch = 0.0;
  49144. this._sinYaw = 0.0;
  49145. this._cosYaw = 0.0;
  49146. this._mustUnrotateFixedNormals = false;
  49147. this._minimum = BABYLON.Tmp.Vector3[0];
  49148. this._maximum = BABYLON.Tmp.Vector3[1];
  49149. this._minBbox = BABYLON.Tmp.Vector3[4];
  49150. this._maxBbox = BABYLON.Tmp.Vector3[5];
  49151. this._particlesIntersect = false;
  49152. this._depthSortFunction = function (p1, p2) {
  49153. return (p2.sqDistance - p1.sqDistance);
  49154. };
  49155. this._needs32Bits = false;
  49156. this.name = name;
  49157. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  49158. this._camera = scene.activeCamera;
  49159. this._pickable = options ? options.isPickable : false;
  49160. this._depthSort = options ? options.enableDepthSort : false;
  49161. this._particlesIntersect = options ? options.particleIntersection : false;
  49162. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  49163. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  49164. if (options && options.updatable) {
  49165. this._updatable = options.updatable;
  49166. }
  49167. else {
  49168. this._updatable = true;
  49169. }
  49170. if (this._pickable) {
  49171. this.pickedParticles = [];
  49172. }
  49173. if (this._depthSort) {
  49174. this.depthSortedParticles = [];
  49175. }
  49176. }
  49177. /**
  49178. * Builds the SPS underlying mesh. Returns a standard Mesh.
  49179. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  49180. * @returns the created mesh
  49181. */
  49182. SolidParticleSystem.prototype.buildMesh = function () {
  49183. if (this.nbParticles === 0) {
  49184. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  49185. this.addShape(triangle, 1);
  49186. triangle.dispose();
  49187. }
  49188. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  49189. this._positions32 = new Float32Array(this._positions);
  49190. this._uvs32 = new Float32Array(this._uvs);
  49191. this._colors32 = new Float32Array(this._colors);
  49192. if (this.recomputeNormals) {
  49193. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  49194. }
  49195. this._normals32 = new Float32Array(this._normals);
  49196. this._fixedNormal32 = new Float32Array(this._normals);
  49197. if (this._mustUnrotateFixedNormals) {
  49198. this._unrotateFixedNormals();
  49199. }
  49200. var vertexData = new BABYLON.VertexData();
  49201. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  49202. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  49203. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  49204. if (this._uvs32) {
  49205. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  49206. ;
  49207. }
  49208. if (this._colors32) {
  49209. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  49210. }
  49211. var mesh = new BABYLON.Mesh(this.name, this._scene);
  49212. vertexData.applyToMesh(mesh, this._updatable);
  49213. this.mesh = mesh;
  49214. this.mesh.isPickable = this._pickable;
  49215. // free memory
  49216. if (!this._depthSort) {
  49217. this._indices = null;
  49218. }
  49219. this._positions = null;
  49220. this._normals = null;
  49221. this._uvs = null;
  49222. this._colors = null;
  49223. if (!this._updatable) {
  49224. this.particles.length = 0;
  49225. }
  49226. return mesh;
  49227. };
  49228. /**
  49229. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  49230. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  49231. * Thus the particles generated from `digest()` have their property `position` set yet.
  49232. * @param mesh ( Mesh ) is the mesh to be digested
  49233. * @param options {facetNb} (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  49234. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  49235. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  49236. * @returns the current SPS
  49237. */
  49238. SolidParticleSystem.prototype.digest = function (mesh, options) {
  49239. var size = (options && options.facetNb) || 1;
  49240. var number = (options && options.number) || 0;
  49241. var delta = (options && options.delta) || 0;
  49242. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49243. var meshInd = mesh.getIndices();
  49244. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49245. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  49246. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49247. var f = 0; // facet counter
  49248. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  49249. // compute size from number
  49250. if (number) {
  49251. number = (number > totalFacets) ? totalFacets : number;
  49252. size = Math.round(totalFacets / number);
  49253. delta = 0;
  49254. }
  49255. else {
  49256. size = (size > totalFacets) ? totalFacets : size;
  49257. }
  49258. var facetPos = []; // submesh positions
  49259. var facetInd = []; // submesh indices
  49260. var facetUV = []; // submesh UV
  49261. var facetCol = []; // submesh colors
  49262. var barycenter = BABYLON.Tmp.Vector3[0];
  49263. var sizeO = size;
  49264. while (f < totalFacets) {
  49265. size = sizeO + Math.floor((1 + delta) * Math.random());
  49266. if (f > totalFacets - size) {
  49267. size = totalFacets - f;
  49268. }
  49269. // reset temp arrays
  49270. facetPos.length = 0;
  49271. facetInd.length = 0;
  49272. facetUV.length = 0;
  49273. facetCol.length = 0;
  49274. // iterate over "size" facets
  49275. var fi = 0;
  49276. for (var j = f * 3; j < (f + size) * 3; j++) {
  49277. facetInd.push(fi);
  49278. var i = meshInd[j];
  49279. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  49280. if (meshUV) {
  49281. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  49282. }
  49283. if (meshCol) {
  49284. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  49285. }
  49286. fi++;
  49287. }
  49288. // create a model shape for each single particle
  49289. var idx = this.nbParticles;
  49290. var shape = this._posToShape(facetPos);
  49291. var shapeUV = this._uvsToShapeUV(facetUV);
  49292. // compute the barycenter of the shape
  49293. var v;
  49294. for (v = 0; v < shape.length; v++) {
  49295. barycenter.addInPlace(shape[v]);
  49296. }
  49297. barycenter.scaleInPlace(1 / shape.length);
  49298. // shift the shape from its barycenter to the origin
  49299. for (v = 0; v < shape.length; v++) {
  49300. shape[v].subtractInPlace(barycenter);
  49301. }
  49302. var bInfo;
  49303. if (this._particlesIntersect) {
  49304. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  49305. }
  49306. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  49307. // add the particle in the SPS
  49308. var currentPos = this._positions.length;
  49309. var currentInd = this._indices.length;
  49310. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  49311. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  49312. // initialize the particle position
  49313. this.particles[this.nbParticles].position.addInPlace(barycenter);
  49314. this._index += shape.length;
  49315. idx++;
  49316. this.nbParticles++;
  49317. this._shapeCounter++;
  49318. f += size;
  49319. }
  49320. return this;
  49321. };
  49322. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  49323. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  49324. var index = 0;
  49325. var idx = 0;
  49326. for (var p = 0; p < this.particles.length; p++) {
  49327. this._particle = this.particles[p];
  49328. this._shape = this._particle._model._shape;
  49329. if (this._particle.rotationQuaternion) {
  49330. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  49331. }
  49332. else {
  49333. this._yaw = this._particle.rotation.y;
  49334. this._pitch = this._particle.rotation.x;
  49335. this._roll = this._particle.rotation.z;
  49336. this._quaternionRotationYPR();
  49337. }
  49338. this._quaternionToRotationMatrix();
  49339. this._rotMatrix.invertToRef(this._invertMatrix);
  49340. for (var pt = 0; pt < this._shape.length; pt++) {
  49341. idx = index + pt * 3;
  49342. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  49343. this._fixedNormal32[idx] = this._normal.x;
  49344. this._fixedNormal32[idx + 1] = this._normal.y;
  49345. this._fixedNormal32[idx + 2] = this._normal.z;
  49346. }
  49347. index = idx + 3;
  49348. }
  49349. };
  49350. //reset copy
  49351. SolidParticleSystem.prototype._resetCopy = function () {
  49352. this._copy.position.x = 0;
  49353. this._copy.position.y = 0;
  49354. this._copy.position.z = 0;
  49355. this._copy.rotation.x = 0;
  49356. this._copy.rotation.y = 0;
  49357. this._copy.rotation.z = 0;
  49358. this._copy.rotationQuaternion = null;
  49359. this._copy.scaling.x = 1.0;
  49360. this._copy.scaling.y = 1.0;
  49361. this._copy.scaling.z = 1.0;
  49362. this._copy.uvs.x = 0;
  49363. this._copy.uvs.y = 0;
  49364. this._copy.uvs.z = 1.0;
  49365. this._copy.uvs.w = 1.0;
  49366. this._copy.color = null;
  49367. };
  49368. // _meshBuilder : inserts the shape model in the global SPS mesh
  49369. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  49370. var i;
  49371. var u = 0;
  49372. var c = 0;
  49373. var n = 0;
  49374. this._resetCopy();
  49375. if (options && options.positionFunction) {
  49376. options.positionFunction(this._copy, idx, idxInShape);
  49377. this._mustUnrotateFixedNormals = true;
  49378. }
  49379. if (this._copy.rotationQuaternion) {
  49380. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  49381. }
  49382. else {
  49383. this._yaw = this._copy.rotation.y;
  49384. this._pitch = this._copy.rotation.x;
  49385. this._roll = this._copy.rotation.z;
  49386. this._quaternionRotationYPR();
  49387. }
  49388. this._quaternionToRotationMatrix();
  49389. for (i = 0; i < shape.length; i++) {
  49390. this._vertex.x = shape[i].x;
  49391. this._vertex.y = shape[i].y;
  49392. this._vertex.z = shape[i].z;
  49393. if (options && options.vertexFunction) {
  49394. options.vertexFunction(this._copy, this._vertex, i);
  49395. }
  49396. this._vertex.x *= this._copy.scaling.x;
  49397. this._vertex.y *= this._copy.scaling.y;
  49398. this._vertex.z *= this._copy.scaling.z;
  49399. this._vertex.x += this._copy.pivot.x;
  49400. this._vertex.y += this._copy.pivot.y;
  49401. this._vertex.z += this._copy.pivot.z;
  49402. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  49403. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  49404. if (meshUV) {
  49405. 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);
  49406. u += 2;
  49407. }
  49408. if (this._copy.color) {
  49409. this._color = this._copy.color;
  49410. }
  49411. else if (meshCol && meshCol[c] !== undefined) {
  49412. this._color.r = meshCol[c];
  49413. this._color.g = meshCol[c + 1];
  49414. this._color.b = meshCol[c + 2];
  49415. this._color.a = meshCol[c + 3];
  49416. }
  49417. else {
  49418. this._color.r = 1.0;
  49419. this._color.g = 1.0;
  49420. this._color.b = 1.0;
  49421. this._color.a = 1.0;
  49422. }
  49423. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  49424. c += 4;
  49425. if (!this.recomputeNormals && meshNor) {
  49426. this._normal.x = meshNor[n];
  49427. this._normal.y = meshNor[n + 1];
  49428. this._normal.z = meshNor[n + 2];
  49429. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  49430. normals.push(this._normal.x, this._normal.y, this._normal.z);
  49431. n += 3;
  49432. }
  49433. }
  49434. for (i = 0; i < meshInd.length; i++) {
  49435. var current_ind = p + meshInd[i];
  49436. indices.push(current_ind);
  49437. if (current_ind > 65535) {
  49438. this._needs32Bits = true;
  49439. }
  49440. }
  49441. if (this._pickable) {
  49442. var nbfaces = meshInd.length / 3;
  49443. for (i = 0; i < nbfaces; i++) {
  49444. this.pickedParticles.push({ idx: idx, faceId: i });
  49445. }
  49446. }
  49447. if (this._depthSort) {
  49448. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  49449. }
  49450. return this._copy;
  49451. };
  49452. // returns a shape array from positions array
  49453. SolidParticleSystem.prototype._posToShape = function (positions) {
  49454. var shape = [];
  49455. for (var i = 0; i < positions.length; i += 3) {
  49456. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  49457. }
  49458. return shape;
  49459. };
  49460. // returns a shapeUV array from a Vector4 uvs
  49461. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  49462. var shapeUV = [];
  49463. if (uvs) {
  49464. for (var i = 0; i < uvs.length; i++)
  49465. shapeUV.push(uvs[i]);
  49466. }
  49467. return shapeUV;
  49468. };
  49469. // adds a new particle object in the particles array
  49470. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  49471. if (bInfo === void 0) { bInfo = null; }
  49472. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  49473. this.particles.push(sp);
  49474. return sp;
  49475. };
  49476. /**
  49477. * Adds some particles to the SPS from the model shape. Returns the shape id.
  49478. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  49479. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  49480. * @param nb (positive integer) the number of particles to be created from this model
  49481. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  49482. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  49483. * @returns the number of shapes in the system
  49484. */
  49485. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  49486. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49487. var meshInd = mesh.getIndices();
  49488. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49489. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  49490. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49491. var bbInfo;
  49492. if (this._particlesIntersect) {
  49493. bbInfo = mesh.getBoundingInfo();
  49494. }
  49495. var shape = this._posToShape(meshPos);
  49496. var shapeUV = this._uvsToShapeUV(meshUV);
  49497. var posfunc = options ? options.positionFunction : null;
  49498. var vtxfunc = options ? options.vertexFunction : null;
  49499. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  49500. // particles
  49501. var sp;
  49502. var currentCopy;
  49503. var idx = this.nbParticles;
  49504. for (var i = 0; i < nb; i++) {
  49505. var currentPos = this._positions.length;
  49506. var currentInd = this._indices.length;
  49507. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  49508. if (this._updatable) {
  49509. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  49510. sp.position.copyFrom(currentCopy.position);
  49511. sp.rotation.copyFrom(currentCopy.rotation);
  49512. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  49513. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  49514. }
  49515. if (currentCopy.color && sp.color) {
  49516. sp.color.copyFrom(currentCopy.color);
  49517. }
  49518. sp.scaling.copyFrom(currentCopy.scaling);
  49519. sp.uvs.copyFrom(currentCopy.uvs);
  49520. }
  49521. this._index += shape.length;
  49522. idx++;
  49523. }
  49524. this.nbParticles += nb;
  49525. this._shapeCounter++;
  49526. return this._shapeCounter - 1;
  49527. };
  49528. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  49529. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  49530. this._resetCopy();
  49531. if (particle._model._positionFunction) {
  49532. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  49533. }
  49534. if (this._copy.rotationQuaternion) {
  49535. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  49536. }
  49537. else {
  49538. this._yaw = this._copy.rotation.y;
  49539. this._pitch = this._copy.rotation.x;
  49540. this._roll = this._copy.rotation.z;
  49541. this._quaternionRotationYPR();
  49542. }
  49543. this._quaternionToRotationMatrix();
  49544. this._shape = particle._model._shape;
  49545. for (var pt = 0; pt < this._shape.length; pt++) {
  49546. this._vertex.x = this._shape[pt].x;
  49547. this._vertex.y = this._shape[pt].y;
  49548. this._vertex.z = this._shape[pt].z;
  49549. if (particle._model._vertexFunction) {
  49550. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  49551. }
  49552. this._vertex.x *= this._copy.scaling.x;
  49553. this._vertex.y *= this._copy.scaling.y;
  49554. this._vertex.z *= this._copy.scaling.z;
  49555. this._vertex.x += this._copy.pivot.x;
  49556. this._vertex.y += this._copy.pivot.y;
  49557. this._vertex.z += this._copy.pivot.z;
  49558. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  49559. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  49560. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  49561. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  49562. }
  49563. particle.position.x = 0.0;
  49564. particle.position.y = 0.0;
  49565. particle.position.z = 0.0;
  49566. particle.rotation.x = 0.0;
  49567. particle.rotation.y = 0.0;
  49568. particle.rotation.z = 0.0;
  49569. particle.rotationQuaternion = null;
  49570. particle.scaling.x = 1.0;
  49571. particle.scaling.y = 1.0;
  49572. particle.scaling.z = 1.0;
  49573. };
  49574. /**
  49575. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  49576. * @returns the SPS.
  49577. */
  49578. SolidParticleSystem.prototype.rebuildMesh = function () {
  49579. for (var p = 0; p < this.particles.length; p++) {
  49580. this._rebuildParticle(this.particles[p]);
  49581. }
  49582. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  49583. return this;
  49584. };
  49585. /**
  49586. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  49587. * This method calls `updateParticle()` for each particle of the SPS.
  49588. * For an animated SPS, it is usually called within the render loop.
  49589. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  49590. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  49591. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  49592. * @returns the SPS.
  49593. */
  49594. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  49595. if (start === void 0) { start = 0; }
  49596. if (end === void 0) { end = this.nbParticles - 1; }
  49597. if (update === void 0) { update = true; }
  49598. if (!this._updatable) {
  49599. return this;
  49600. }
  49601. // custom beforeUpdate
  49602. this.beforeUpdateParticles(start, end, update);
  49603. this._cam_axisX.x = 1.0;
  49604. this._cam_axisX.y = 0.0;
  49605. this._cam_axisX.z = 0.0;
  49606. this._cam_axisY.x = 0.0;
  49607. this._cam_axisY.y = 1.0;
  49608. this._cam_axisY.z = 0.0;
  49609. this._cam_axisZ.x = 0.0;
  49610. this._cam_axisZ.y = 0.0;
  49611. this._cam_axisZ.z = 1.0;
  49612. // cases when the World Matrix is to be computed first
  49613. if (this.billboard || this._depthSort) {
  49614. this.mesh.computeWorldMatrix(true);
  49615. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  49616. }
  49617. // if the particles will always face the camera
  49618. if (this.billboard) {
  49619. // compute the camera position and un-rotate it by the current mesh rotation
  49620. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  49621. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  49622. this._cam_axisZ.normalize();
  49623. // same for camera up vector extracted from the cam view matrix
  49624. var view = this._camera.getViewMatrix(true);
  49625. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  49626. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  49627. this._cam_axisY.normalize();
  49628. this._cam_axisX.normalize();
  49629. }
  49630. // if depthSort, compute the camera global position in the mesh local system
  49631. if (this._depthSort) {
  49632. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  49633. }
  49634. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  49635. var idx = 0; // current position index in the global array positions32
  49636. var index = 0; // position start index in the global array positions32 of the current particle
  49637. var colidx = 0; // current color index in the global array colors32
  49638. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  49639. var uvidx = 0; // current uv index in the global array uvs32
  49640. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  49641. var pt = 0; // current index in the particle model shape
  49642. if (this.mesh.isFacetDataEnabled) {
  49643. this._computeBoundingBox = true;
  49644. }
  49645. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  49646. if (this._computeBoundingBox) {
  49647. if (start == 0 && end == this.nbParticles - 1) {
  49648. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  49649. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  49650. }
  49651. else {
  49652. if (this.mesh._boundingInfo) {
  49653. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  49654. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  49655. }
  49656. }
  49657. }
  49658. // particle loop
  49659. index = this.particles[start]._pos;
  49660. var vpos = (index / 3) | 0;
  49661. colorIndex = vpos * 4;
  49662. uvIndex = vpos * 2;
  49663. for (var p = start; p <= end; p++) {
  49664. this._particle = this.particles[p];
  49665. this._shape = this._particle._model._shape;
  49666. this._shapeUV = this._particle._model._shapeUV;
  49667. // call to custom user function to update the particle properties
  49668. this.updateParticle(this._particle);
  49669. // camera-particle distance for depth sorting
  49670. if (this._depthSort && this._depthSortParticles) {
  49671. var dsp = this.depthSortedParticles[p];
  49672. dsp.ind = this._particle._ind;
  49673. dsp.indicesLength = this._particle._model._indicesLength;
  49674. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  49675. }
  49676. // skip the computations for inactive or already invisible particles
  49677. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  49678. // increment indexes for the next particle
  49679. pt = this._shape.length;
  49680. index += pt * 3;
  49681. colorIndex += pt * 4;
  49682. uvIndex += pt * 2;
  49683. continue;
  49684. }
  49685. if (this._particle.isVisible) {
  49686. this._particle._stillInvisible = false; // un-mark permanent invisibility
  49687. // particle rotation matrix
  49688. if (this.billboard) {
  49689. this._particle.rotation.x = 0.0;
  49690. this._particle.rotation.y = 0.0;
  49691. }
  49692. if (this._computeParticleRotation || this.billboard) {
  49693. if (this._particle.rotationQuaternion) {
  49694. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  49695. }
  49696. else {
  49697. this._yaw = this._particle.rotation.y;
  49698. this._pitch = this._particle.rotation.x;
  49699. this._roll = this._particle.rotation.z;
  49700. this._quaternionRotationYPR();
  49701. }
  49702. this._quaternionToRotationMatrix();
  49703. }
  49704. // particle vertex loop
  49705. for (pt = 0; pt < this._shape.length; pt++) {
  49706. idx = index + pt * 3;
  49707. colidx = colorIndex + pt * 4;
  49708. uvidx = uvIndex + pt * 2;
  49709. this._vertex.x = this._shape[pt].x;
  49710. this._vertex.y = this._shape[pt].y;
  49711. this._vertex.z = this._shape[pt].z;
  49712. if (this._computeParticleVertex) {
  49713. this.updateParticleVertex(this._particle, this._vertex, pt);
  49714. }
  49715. // positions
  49716. this._vertex.x *= this._particle.scaling.x;
  49717. this._vertex.y *= this._particle.scaling.y;
  49718. this._vertex.z *= this._particle.scaling.z;
  49719. this._vertex.x += this._particle.pivot.x;
  49720. this._vertex.y += this._particle.pivot.y;
  49721. this._vertex.z += this._particle.pivot.z;
  49722. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  49723. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  49724. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  49725. 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;
  49726. 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;
  49727. 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;
  49728. if (this._computeBoundingBox) {
  49729. if (this._positions32[idx] < this._minimum.x) {
  49730. this._minimum.x = this._positions32[idx];
  49731. }
  49732. if (this._positions32[idx] > this._maximum.x) {
  49733. this._maximum.x = this._positions32[idx];
  49734. }
  49735. if (this._positions32[idx + 1] < this._minimum.y) {
  49736. this._minimum.y = this._positions32[idx + 1];
  49737. }
  49738. if (this._positions32[idx + 1] > this._maximum.y) {
  49739. this._maximum.y = this._positions32[idx + 1];
  49740. }
  49741. if (this._positions32[idx + 2] < this._minimum.z) {
  49742. this._minimum.z = this._positions32[idx + 2];
  49743. }
  49744. if (this._positions32[idx + 2] > this._maximum.z) {
  49745. this._maximum.z = this._positions32[idx + 2];
  49746. }
  49747. }
  49748. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  49749. if (!this._computeParticleVertex) {
  49750. this._normal.x = this._fixedNormal32[idx];
  49751. this._normal.y = this._fixedNormal32[idx + 1];
  49752. this._normal.z = this._fixedNormal32[idx + 2];
  49753. this._rotated.x = this._normal.x * this._rotMatrix.m[0] + this._normal.y * this._rotMatrix.m[4] + this._normal.z * this._rotMatrix.m[8];
  49754. this._rotated.y = this._normal.x * this._rotMatrix.m[1] + this._normal.y * this._rotMatrix.m[5] + this._normal.z * this._rotMatrix.m[9];
  49755. this._rotated.z = this._normal.x * this._rotMatrix.m[2] + this._normal.y * this._rotMatrix.m[6] + this._normal.z * this._rotMatrix.m[10];
  49756. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  49757. 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;
  49758. 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;
  49759. }
  49760. if (this._computeParticleColor && this._particle.color) {
  49761. this._colors32[colidx] = this._particle.color.r;
  49762. this._colors32[colidx + 1] = this._particle.color.g;
  49763. this._colors32[colidx + 2] = this._particle.color.b;
  49764. this._colors32[colidx + 3] = this._particle.color.a;
  49765. }
  49766. if (this._computeParticleTexture) {
  49767. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  49768. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  49769. }
  49770. }
  49771. }
  49772. else {
  49773. this._particle._stillInvisible = true; // mark the particle as invisible
  49774. for (pt = 0; pt < this._shape.length; pt++) {
  49775. idx = index + pt * 3;
  49776. colidx = colorIndex + pt * 4;
  49777. uvidx = uvIndex + pt * 2;
  49778. this._positions32[idx] = 0.0;
  49779. this._positions32[idx + 1] = 0.0;
  49780. this._positions32[idx + 2] = 0.0;
  49781. this._normals32[idx] = 0.0;
  49782. this._normals32[idx + 1] = 0.0;
  49783. this._normals32[idx + 2] = 0.0;
  49784. if (this._computeParticleColor && this._particle.color) {
  49785. this._colors32[colidx] = this._particle.color.r;
  49786. this._colors32[colidx + 1] = this._particle.color.g;
  49787. this._colors32[colidx + 2] = this._particle.color.b;
  49788. this._colors32[colidx + 3] = this._particle.color.a;
  49789. }
  49790. if (this._computeParticleTexture) {
  49791. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  49792. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  49793. }
  49794. }
  49795. }
  49796. // if the particle intersections must be computed : update the bbInfo
  49797. if (this._particlesIntersect) {
  49798. var bInfo = this._particle._boundingInfo;
  49799. var bBox = bInfo.boundingBox;
  49800. var bSphere = bInfo.boundingSphere;
  49801. if (!this._bSphereOnly) {
  49802. // place, scale and rotate the particle bbox within the SPS local system, then update it
  49803. for (var b = 0; b < bBox.vectors.length; b++) {
  49804. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  49805. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  49806. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  49807. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  49808. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  49809. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  49810. 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;
  49811. 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;
  49812. 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;
  49813. }
  49814. bBox._update(this.mesh._worldMatrix);
  49815. }
  49816. // place and scale the particle bouding sphere in the SPS local system, then update it
  49817. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  49818. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  49819. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  49820. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  49821. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  49822. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  49823. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  49824. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  49825. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  49826. 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));
  49827. bSphere._update(this.mesh._worldMatrix);
  49828. }
  49829. // increment indexes for the next particle
  49830. index = idx + 3;
  49831. colorIndex = colidx + 4;
  49832. uvIndex = uvidx + 2;
  49833. }
  49834. // if the VBO must be updated
  49835. if (update) {
  49836. if (this._computeParticleColor) {
  49837. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  49838. }
  49839. if (this._computeParticleTexture) {
  49840. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  49841. }
  49842. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  49843. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  49844. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  49845. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  49846. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  49847. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  49848. for (var i = 0; i < this._normals32.length; i++) {
  49849. this._fixedNormal32[i] = this._normals32[i];
  49850. }
  49851. }
  49852. if (!this.mesh.areNormalsFrozen) {
  49853. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  49854. }
  49855. }
  49856. if (this._depthSort && this._depthSortParticles) {
  49857. this.depthSortedParticles.sort(this._depthSortFunction);
  49858. var dspl = this.depthSortedParticles.length;
  49859. var sorted = 0;
  49860. var lind = 0;
  49861. var sind = 0;
  49862. var sid = 0;
  49863. for (sorted = 0; sorted < dspl; sorted++) {
  49864. lind = this.depthSortedParticles[sorted].indicesLength;
  49865. sind = this.depthSortedParticles[sorted].ind;
  49866. for (var i = 0; i < lind; i++) {
  49867. this._indices32[sid] = this._indices[sind + i];
  49868. sid++;
  49869. }
  49870. }
  49871. this.mesh.updateIndices(this._indices32);
  49872. }
  49873. }
  49874. if (this._computeBoundingBox) {
  49875. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  49876. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  49877. }
  49878. this.afterUpdateParticles(start, end, update);
  49879. return this;
  49880. };
  49881. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  49882. this._halfroll = this._roll * 0.5;
  49883. this._halfpitch = this._pitch * 0.5;
  49884. this._halfyaw = this._yaw * 0.5;
  49885. this._sinRoll = Math.sin(this._halfroll);
  49886. this._cosRoll = Math.cos(this._halfroll);
  49887. this._sinPitch = Math.sin(this._halfpitch);
  49888. this._cosPitch = Math.cos(this._halfpitch);
  49889. this._sinYaw = Math.sin(this._halfyaw);
  49890. this._cosYaw = Math.cos(this._halfyaw);
  49891. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  49892. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  49893. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  49894. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  49895. };
  49896. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  49897. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  49898. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  49899. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  49900. this._rotMatrix.m[3] = 0;
  49901. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  49902. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  49903. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  49904. this._rotMatrix.m[7] = 0;
  49905. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  49906. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  49907. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  49908. this._rotMatrix.m[11] = 0;
  49909. this._rotMatrix.m[12] = 0;
  49910. this._rotMatrix.m[13] = 0;
  49911. this._rotMatrix.m[14] = 0;
  49912. this._rotMatrix.m[15] = 1.0;
  49913. };
  49914. /**
  49915. * Disposes the SPS.
  49916. */
  49917. SolidParticleSystem.prototype.dispose = function () {
  49918. this.mesh.dispose();
  49919. this.vars = null;
  49920. // drop references to internal big arrays for the GC
  49921. this._positions = null;
  49922. this._indices = null;
  49923. this._normals = null;
  49924. this._uvs = null;
  49925. this._colors = null;
  49926. this._indices32 = null;
  49927. this._positions32 = null;
  49928. this._normals32 = null;
  49929. this._fixedNormal32 = null;
  49930. this._uvs32 = null;
  49931. this._colors32 = null;
  49932. this.pickedParticles = null;
  49933. };
  49934. /**
  49935. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  49936. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49937. * @returns the SPS.
  49938. */
  49939. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  49940. if (!this._isVisibilityBoxLocked) {
  49941. this.mesh.refreshBoundingInfo();
  49942. }
  49943. return this;
  49944. };
  49945. /**
  49946. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  49947. * @param size the size (float) of the visibility box
  49948. * note : this doesn't lock the SPS mesh bounding box.
  49949. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49950. */
  49951. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  49952. var vis = size / 2;
  49953. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  49954. };
  49955. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  49956. /**
  49957. * Gets whether the SPS as always visible or not
  49958. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49959. */
  49960. get: function () {
  49961. return this._alwaysVisible;
  49962. },
  49963. /**
  49964. * Sets the SPS as always visible or not
  49965. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49966. */
  49967. set: function (val) {
  49968. this._alwaysVisible = val;
  49969. this.mesh.alwaysSelectAsActiveMesh = val;
  49970. },
  49971. enumerable: true,
  49972. configurable: true
  49973. });
  49974. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  49975. /**
  49976. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  49977. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49978. */
  49979. get: function () {
  49980. return this._isVisibilityBoxLocked;
  49981. },
  49982. /**
  49983. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  49984. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49985. */
  49986. set: function (val) {
  49987. this._isVisibilityBoxLocked = val;
  49988. var boundingInfo = this.mesh.getBoundingInfo();
  49989. boundingInfo.isLocked = val;
  49990. },
  49991. enumerable: true,
  49992. configurable: true
  49993. });
  49994. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  49995. /**
  49996. * Gets if `setParticles()` computes the particle rotations or not.
  49997. * Default value : true. The SPS is faster when it's set to false.
  49998. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  49999. */
  50000. get: function () {
  50001. return this._computeParticleRotation;
  50002. },
  50003. /**
  50004. * Tells to `setParticles()` to compute the particle rotations or not.
  50005. * Default value : true. The SPS is faster when it's set to false.
  50006. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  50007. */
  50008. set: function (val) {
  50009. this._computeParticleRotation = val;
  50010. },
  50011. enumerable: true,
  50012. configurable: true
  50013. });
  50014. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  50015. /**
  50016. * Gets if `setParticles()` computes the particle colors or not.
  50017. * Default value : true. The SPS is faster when it's set to false.
  50018. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  50019. */
  50020. get: function () {
  50021. return this._computeParticleColor;
  50022. },
  50023. /**
  50024. * Tells to `setParticles()` to compute the particle colors or not.
  50025. * Default value : true. The SPS is faster when it's set to false.
  50026. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  50027. */
  50028. set: function (val) {
  50029. this._computeParticleColor = val;
  50030. },
  50031. enumerable: true,
  50032. configurable: true
  50033. });
  50034. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  50035. /**
  50036. * Gets if `setParticles()` computes the particle textures or not.
  50037. * Default value : true. The SPS is faster when it's set to false.
  50038. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  50039. */
  50040. get: function () {
  50041. return this._computeParticleTexture;
  50042. },
  50043. set: function (val) {
  50044. this._computeParticleTexture = val;
  50045. },
  50046. enumerable: true,
  50047. configurable: true
  50048. });
  50049. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  50050. /**
  50051. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  50052. * Default value : false. The SPS is faster when it's set to false.
  50053. * Note : the particle custom vertex positions aren't stored values.
  50054. */
  50055. get: function () {
  50056. return this._computeParticleVertex;
  50057. },
  50058. /**
  50059. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  50060. * Default value : false. The SPS is faster when it's set to false.
  50061. * Note : the particle custom vertex positions aren't stored values.
  50062. */
  50063. set: function (val) {
  50064. this._computeParticleVertex = val;
  50065. },
  50066. enumerable: true,
  50067. configurable: true
  50068. });
  50069. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  50070. /**
  50071. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  50072. */
  50073. get: function () {
  50074. return this._computeBoundingBox;
  50075. },
  50076. /**
  50077. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  50078. */
  50079. set: function (val) {
  50080. this._computeBoundingBox = val;
  50081. },
  50082. enumerable: true,
  50083. configurable: true
  50084. });
  50085. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  50086. /**
  50087. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  50088. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  50089. * Default : `true`
  50090. */
  50091. get: function () {
  50092. return this._depthSortParticles;
  50093. },
  50094. /**
  50095. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  50096. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  50097. * Default : `true`
  50098. */
  50099. set: function (val) {
  50100. this._depthSortParticles = val;
  50101. },
  50102. enumerable: true,
  50103. configurable: true
  50104. });
  50105. // =======================================================================
  50106. // Particle behavior logic
  50107. // these following methods may be overwritten by the user to fit his needs
  50108. /**
  50109. * This function does nothing. It may be overwritten to set all the particle first values.
  50110. * The SPS doesn't call this function, you may have to call it by your own.
  50111. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  50112. */
  50113. SolidParticleSystem.prototype.initParticles = function () {
  50114. };
  50115. /**
  50116. * This function does nothing. It may be overwritten to recycle a particle.
  50117. * The SPS doesn't call this function, you may have to call it by your own.
  50118. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  50119. * @param particle The particle to recycle
  50120. * @returns the recycled particle
  50121. */
  50122. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  50123. return particle;
  50124. };
  50125. /**
  50126. * Updates a particle : this function should be overwritten by the user.
  50127. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  50128. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  50129. * @example : just set a particle position or velocity and recycle conditions
  50130. * @param particle The particle to update
  50131. * @returns the updated particle
  50132. */
  50133. SolidParticleSystem.prototype.updateParticle = function (particle) {
  50134. return particle;
  50135. };
  50136. /**
  50137. * Updates a vertex of a particle : it can be overwritten by the user.
  50138. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  50139. * @param particle the current particle
  50140. * @param vertex the current index of the current particle
  50141. * @param pt the index of the current vertex in the particle shape
  50142. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  50143. * @example : just set a vertex particle position
  50144. * @returns the updated vertex
  50145. */
  50146. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  50147. return vertex;
  50148. };
  50149. /**
  50150. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  50151. * This does nothing and may be overwritten by the user.
  50152. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50153. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50154. * @param update the boolean update value actually passed to setParticles()
  50155. */
  50156. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  50157. };
  50158. /**
  50159. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  50160. * This will be passed three parameters.
  50161. * This does nothing and may be overwritten by the user.
  50162. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50163. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50164. * @param update the boolean update value actually passed to setParticles()
  50165. */
  50166. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  50167. };
  50168. return SolidParticleSystem;
  50169. }());
  50170. BABYLON.SolidParticleSystem = SolidParticleSystem;
  50171. })(BABYLON || (BABYLON = {}));
  50172. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  50173. var BABYLON;
  50174. (function (BABYLON) {
  50175. var ShaderMaterial = /** @class */ (function (_super) {
  50176. __extends(ShaderMaterial, _super);
  50177. function ShaderMaterial(name, scene, shaderPath, options) {
  50178. var _this = _super.call(this, name, scene) || this;
  50179. _this._textures = {};
  50180. _this._textureArrays = {};
  50181. _this._floats = {};
  50182. _this._ints = {};
  50183. _this._floatsArrays = {};
  50184. _this._colors3 = {};
  50185. _this._colors3Arrays = {};
  50186. _this._colors4 = {};
  50187. _this._vectors2 = {};
  50188. _this._vectors3 = {};
  50189. _this._vectors4 = {};
  50190. _this._matrices = {};
  50191. _this._matrices3x3 = {};
  50192. _this._matrices2x2 = {};
  50193. _this._vectors2Arrays = {};
  50194. _this._vectors3Arrays = {};
  50195. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  50196. _this._shaderPath = shaderPath;
  50197. options.needAlphaBlending = options.needAlphaBlending || false;
  50198. options.needAlphaTesting = options.needAlphaTesting || false;
  50199. options.attributes = options.attributes || ["position", "normal", "uv"];
  50200. options.uniforms = options.uniforms || ["worldViewProjection"];
  50201. options.uniformBuffers = options.uniformBuffers || [];
  50202. options.samplers = options.samplers || [];
  50203. options.defines = options.defines || [];
  50204. _this._options = options;
  50205. return _this;
  50206. }
  50207. ShaderMaterial.prototype.getClassName = function () {
  50208. return "ShaderMaterial";
  50209. };
  50210. ShaderMaterial.prototype.needAlphaBlending = function () {
  50211. return this._options.needAlphaBlending;
  50212. };
  50213. ShaderMaterial.prototype.needAlphaTesting = function () {
  50214. return this._options.needAlphaTesting;
  50215. };
  50216. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  50217. if (this._options.uniforms.indexOf(uniformName) === -1) {
  50218. this._options.uniforms.push(uniformName);
  50219. }
  50220. };
  50221. ShaderMaterial.prototype.setTexture = function (name, texture) {
  50222. if (this._options.samplers.indexOf(name) === -1) {
  50223. this._options.samplers.push(name);
  50224. }
  50225. this._textures[name] = texture;
  50226. return this;
  50227. };
  50228. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  50229. if (this._options.samplers.indexOf(name) === -1) {
  50230. this._options.samplers.push(name);
  50231. }
  50232. this._checkUniform(name);
  50233. this._textureArrays[name] = textures;
  50234. return this;
  50235. };
  50236. ShaderMaterial.prototype.setFloat = function (name, value) {
  50237. this._checkUniform(name);
  50238. this._floats[name] = value;
  50239. return this;
  50240. };
  50241. ShaderMaterial.prototype.setInt = function (name, value) {
  50242. this._checkUniform(name);
  50243. this._ints[name] = value;
  50244. return this;
  50245. };
  50246. ShaderMaterial.prototype.setFloats = function (name, value) {
  50247. this._checkUniform(name);
  50248. this._floatsArrays[name] = value;
  50249. return this;
  50250. };
  50251. ShaderMaterial.prototype.setColor3 = function (name, value) {
  50252. this._checkUniform(name);
  50253. this._colors3[name] = value;
  50254. return this;
  50255. };
  50256. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  50257. this._checkUniform(name);
  50258. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  50259. color.toArray(arr, arr.length);
  50260. return arr;
  50261. }, []);
  50262. return this;
  50263. };
  50264. ShaderMaterial.prototype.setColor4 = function (name, value) {
  50265. this._checkUniform(name);
  50266. this._colors4[name] = value;
  50267. return this;
  50268. };
  50269. ShaderMaterial.prototype.setVector2 = function (name, value) {
  50270. this._checkUniform(name);
  50271. this._vectors2[name] = value;
  50272. return this;
  50273. };
  50274. ShaderMaterial.prototype.setVector3 = function (name, value) {
  50275. this._checkUniform(name);
  50276. this._vectors3[name] = value;
  50277. return this;
  50278. };
  50279. ShaderMaterial.prototype.setVector4 = function (name, value) {
  50280. this._checkUniform(name);
  50281. this._vectors4[name] = value;
  50282. return this;
  50283. };
  50284. ShaderMaterial.prototype.setMatrix = function (name, value) {
  50285. this._checkUniform(name);
  50286. this._matrices[name] = value;
  50287. return this;
  50288. };
  50289. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  50290. this._checkUniform(name);
  50291. this._matrices3x3[name] = value;
  50292. return this;
  50293. };
  50294. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  50295. this._checkUniform(name);
  50296. this._matrices2x2[name] = value;
  50297. return this;
  50298. };
  50299. ShaderMaterial.prototype.setArray2 = function (name, value) {
  50300. this._checkUniform(name);
  50301. this._vectors2Arrays[name] = value;
  50302. return this;
  50303. };
  50304. ShaderMaterial.prototype.setArray3 = function (name, value) {
  50305. this._checkUniform(name);
  50306. this._vectors3Arrays[name] = value;
  50307. return this;
  50308. };
  50309. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  50310. if (!mesh) {
  50311. return true;
  50312. }
  50313. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  50314. return false;
  50315. }
  50316. return false;
  50317. };
  50318. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  50319. var scene = this.getScene();
  50320. var engine = scene.getEngine();
  50321. if (!this.checkReadyOnEveryCall) {
  50322. if (this._renderId === scene.getRenderId()) {
  50323. if (this._checkCache(scene, mesh, useInstances)) {
  50324. return true;
  50325. }
  50326. }
  50327. }
  50328. // Instances
  50329. var defines = [];
  50330. var attribs = [];
  50331. var fallbacks = new BABYLON.EffectFallbacks();
  50332. if (useInstances) {
  50333. defines.push("#define INSTANCES");
  50334. }
  50335. for (var index = 0; index < this._options.defines.length; index++) {
  50336. defines.push(this._options.defines[index]);
  50337. }
  50338. for (var index = 0; index < this._options.attributes.length; index++) {
  50339. attribs.push(this._options.attributes[index]);
  50340. }
  50341. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  50342. attribs.push(BABYLON.VertexBuffer.ColorKind);
  50343. defines.push("#define VERTEXCOLOR");
  50344. }
  50345. // Bones
  50346. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  50347. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  50348. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  50349. if (mesh.numBoneInfluencers > 4) {
  50350. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  50351. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  50352. }
  50353. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  50354. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  50355. fallbacks.addCPUSkinningFallback(0, mesh);
  50356. if (this._options.uniforms.indexOf("mBones") === -1) {
  50357. this._options.uniforms.push("mBones");
  50358. }
  50359. }
  50360. else {
  50361. defines.push("#define NUM_BONE_INFLUENCERS 0");
  50362. }
  50363. // Textures
  50364. for (var name in this._textures) {
  50365. if (!this._textures[name].isReady()) {
  50366. return false;
  50367. }
  50368. }
  50369. // Alpha test
  50370. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  50371. defines.push("#define ALPHATEST");
  50372. }
  50373. var previousEffect = this._effect;
  50374. var join = defines.join("\n");
  50375. this._effect = engine.createEffect(this._shaderPath, {
  50376. attributes: attribs,
  50377. uniformsNames: this._options.uniforms,
  50378. uniformBuffersNames: this._options.uniformBuffers,
  50379. samplers: this._options.samplers,
  50380. defines: join,
  50381. fallbacks: fallbacks,
  50382. onCompiled: this.onCompiled,
  50383. onError: this.onError
  50384. }, engine);
  50385. if (!this._effect.isReady()) {
  50386. return false;
  50387. }
  50388. if (previousEffect !== this._effect) {
  50389. scene.resetCachedMaterial();
  50390. }
  50391. this._renderId = scene.getRenderId();
  50392. return true;
  50393. };
  50394. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  50395. var scene = this.getScene();
  50396. if (!this._effect) {
  50397. return;
  50398. }
  50399. if (this._options.uniforms.indexOf("world") !== -1) {
  50400. this._effect.setMatrix("world", world);
  50401. }
  50402. if (this._options.uniforms.indexOf("worldView") !== -1) {
  50403. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  50404. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  50405. }
  50406. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  50407. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  50408. }
  50409. };
  50410. ShaderMaterial.prototype.bind = function (world, mesh) {
  50411. // Std values
  50412. this.bindOnlyWorldMatrix(world);
  50413. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  50414. if (this._options.uniforms.indexOf("view") !== -1) {
  50415. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  50416. }
  50417. if (this._options.uniforms.indexOf("projection") !== -1) {
  50418. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  50419. }
  50420. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  50421. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  50422. }
  50423. // Bones
  50424. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  50425. var name;
  50426. // Texture
  50427. for (name in this._textures) {
  50428. this._effect.setTexture(name, this._textures[name]);
  50429. }
  50430. // Texture arrays
  50431. for (name in this._textureArrays) {
  50432. this._effect.setTextureArray(name, this._textureArrays[name]);
  50433. }
  50434. // Int
  50435. for (name in this._ints) {
  50436. this._effect.setInt(name, this._ints[name]);
  50437. }
  50438. // Float
  50439. for (name in this._floats) {
  50440. this._effect.setFloat(name, this._floats[name]);
  50441. }
  50442. // Floats
  50443. for (name in this._floatsArrays) {
  50444. this._effect.setArray(name, this._floatsArrays[name]);
  50445. }
  50446. // Color3
  50447. for (name in this._colors3) {
  50448. this._effect.setColor3(name, this._colors3[name]);
  50449. }
  50450. for (name in this._colors3Arrays) {
  50451. this._effect.setArray3(name, this._colors3Arrays[name]);
  50452. }
  50453. // Color4
  50454. for (name in this._colors4) {
  50455. var color = this._colors4[name];
  50456. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  50457. }
  50458. // Vector2
  50459. for (name in this._vectors2) {
  50460. this._effect.setVector2(name, this._vectors2[name]);
  50461. }
  50462. // Vector3
  50463. for (name in this._vectors3) {
  50464. this._effect.setVector3(name, this._vectors3[name]);
  50465. }
  50466. // Vector4
  50467. for (name in this._vectors4) {
  50468. this._effect.setVector4(name, this._vectors4[name]);
  50469. }
  50470. // Matrix
  50471. for (name in this._matrices) {
  50472. this._effect.setMatrix(name, this._matrices[name]);
  50473. }
  50474. // Matrix 3x3
  50475. for (name in this._matrices3x3) {
  50476. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  50477. }
  50478. // Matrix 2x2
  50479. for (name in this._matrices2x2) {
  50480. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  50481. }
  50482. // Vector2Array
  50483. for (name in this._vectors2Arrays) {
  50484. this._effect.setArray2(name, this._vectors2Arrays[name]);
  50485. }
  50486. // Vector3Array
  50487. for (name in this._vectors3Arrays) {
  50488. this._effect.setArray3(name, this._vectors3Arrays[name]);
  50489. }
  50490. }
  50491. this._afterBind(mesh);
  50492. };
  50493. ShaderMaterial.prototype.getActiveTextures = function () {
  50494. var activeTextures = _super.prototype.getActiveTextures.call(this);
  50495. for (var name in this._textures) {
  50496. activeTextures.push(this._textures[name]);
  50497. }
  50498. for (var name in this._textureArrays) {
  50499. var array = this._textureArrays[name];
  50500. for (var index = 0; index < array.length; index++) {
  50501. activeTextures.push(array[index]);
  50502. }
  50503. }
  50504. return activeTextures;
  50505. };
  50506. ShaderMaterial.prototype.hasTexture = function (texture) {
  50507. if (_super.prototype.hasTexture.call(this, texture)) {
  50508. return true;
  50509. }
  50510. for (var name in this._textures) {
  50511. if (this._textures[name] === texture) {
  50512. return true;
  50513. }
  50514. }
  50515. for (var name in this._textureArrays) {
  50516. var array = this._textureArrays[name];
  50517. for (var index = 0; index < array.length; index++) {
  50518. if (array[index] === texture) {
  50519. return true;
  50520. }
  50521. }
  50522. }
  50523. return false;
  50524. };
  50525. ShaderMaterial.prototype.clone = function (name) {
  50526. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  50527. return newShaderMaterial;
  50528. };
  50529. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  50530. if (forceDisposeTextures) {
  50531. var name;
  50532. for (name in this._textures) {
  50533. this._textures[name].dispose();
  50534. }
  50535. for (name in this._textureArrays) {
  50536. var array = this._textureArrays[name];
  50537. for (var index = 0; index < array.length; index++) {
  50538. array[index].dispose();
  50539. }
  50540. }
  50541. }
  50542. this._textures = {};
  50543. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  50544. };
  50545. ShaderMaterial.prototype.serialize = function () {
  50546. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  50547. serializationObject.customType = "BABYLON.ShaderMaterial";
  50548. serializationObject.options = this._options;
  50549. serializationObject.shaderPath = this._shaderPath;
  50550. var name;
  50551. // Texture
  50552. serializationObject.textures = {};
  50553. for (name in this._textures) {
  50554. serializationObject.textures[name] = this._textures[name].serialize();
  50555. }
  50556. // Texture arrays
  50557. serializationObject.textureArrays = {};
  50558. for (name in this._textureArrays) {
  50559. serializationObject.textureArrays[name] = [];
  50560. var array = this._textureArrays[name];
  50561. for (var index = 0; index < array.length; index++) {
  50562. serializationObject.textureArrays[name].push(array[index].serialize());
  50563. }
  50564. }
  50565. // Float
  50566. serializationObject.floats = {};
  50567. for (name in this._floats) {
  50568. serializationObject.floats[name] = this._floats[name];
  50569. }
  50570. // Float s
  50571. serializationObject.FloatArrays = {};
  50572. for (name in this._floatsArrays) {
  50573. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  50574. }
  50575. // Color3
  50576. serializationObject.colors3 = {};
  50577. for (name in this._colors3) {
  50578. serializationObject.colors3[name] = this._colors3[name].asArray();
  50579. }
  50580. // Color3 array
  50581. serializationObject.colors3Arrays = {};
  50582. for (name in this._colors3Arrays) {
  50583. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  50584. }
  50585. // Color4
  50586. serializationObject.colors4 = {};
  50587. for (name in this._colors4) {
  50588. serializationObject.colors4[name] = this._colors4[name].asArray();
  50589. }
  50590. // Vector2
  50591. serializationObject.vectors2 = {};
  50592. for (name in this._vectors2) {
  50593. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  50594. }
  50595. // Vector3
  50596. serializationObject.vectors3 = {};
  50597. for (name in this._vectors3) {
  50598. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  50599. }
  50600. // Vector4
  50601. serializationObject.vectors4 = {};
  50602. for (name in this._vectors4) {
  50603. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  50604. }
  50605. // Matrix
  50606. serializationObject.matrices = {};
  50607. for (name in this._matrices) {
  50608. serializationObject.matrices[name] = this._matrices[name].asArray();
  50609. }
  50610. // Matrix 3x3
  50611. serializationObject.matrices3x3 = {};
  50612. for (name in this._matrices3x3) {
  50613. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  50614. }
  50615. // Matrix 2x2
  50616. serializationObject.matrices2x2 = {};
  50617. for (name in this._matrices2x2) {
  50618. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  50619. }
  50620. // Vector2Array
  50621. serializationObject.vectors2Arrays = {};
  50622. for (name in this._vectors2Arrays) {
  50623. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  50624. }
  50625. // Vector3Array
  50626. serializationObject.vectors3Arrays = {};
  50627. for (name in this._vectors3Arrays) {
  50628. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  50629. }
  50630. return serializationObject;
  50631. };
  50632. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  50633. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  50634. var name;
  50635. // Texture
  50636. for (name in source.textures) {
  50637. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  50638. }
  50639. // Texture arrays
  50640. for (name in source.textureArrays) {
  50641. var array = source.textureArrays[name];
  50642. var textureArray = new Array();
  50643. for (var index = 0; index < array.length; index++) {
  50644. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  50645. }
  50646. material.setTextureArray(name, textureArray);
  50647. }
  50648. // Float
  50649. for (name in source.floats) {
  50650. material.setFloat(name, source.floats[name]);
  50651. }
  50652. // Float s
  50653. for (name in source.floatsArrays) {
  50654. material.setFloats(name, source.floatsArrays[name]);
  50655. }
  50656. // Color3
  50657. for (name in source.colors3) {
  50658. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  50659. }
  50660. // Color3 arrays
  50661. for (name in source.colors3Arrays) {
  50662. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  50663. if (i % 3 === 0) {
  50664. arr.push([num]);
  50665. }
  50666. else {
  50667. arr[arr.length - 1].push(num);
  50668. }
  50669. return arr;
  50670. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  50671. material.setColor3Array(name, colors);
  50672. }
  50673. // Color4
  50674. for (name in source.colors4) {
  50675. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  50676. }
  50677. // Vector2
  50678. for (name in source.vectors2) {
  50679. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  50680. }
  50681. // Vector3
  50682. for (name in source.vectors3) {
  50683. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  50684. }
  50685. // Vector4
  50686. for (name in source.vectors4) {
  50687. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  50688. }
  50689. // Matrix
  50690. for (name in source.matrices) {
  50691. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  50692. }
  50693. // Matrix 3x3
  50694. for (name in source.matrices3x3) {
  50695. material.setMatrix3x3(name, source.matrices3x3[name]);
  50696. }
  50697. // Matrix 2x2
  50698. for (name in source.matrices2x2) {
  50699. material.setMatrix2x2(name, source.matrices2x2[name]);
  50700. }
  50701. // Vector2Array
  50702. for (name in source.vectors2Arrays) {
  50703. material.setArray2(name, source.vectors2Arrays[name]);
  50704. }
  50705. // Vector3Array
  50706. for (name in source.vectors3Arrays) {
  50707. material.setArray3(name, source.vectors3Arrays[name]);
  50708. }
  50709. return material;
  50710. };
  50711. return ShaderMaterial;
  50712. }(BABYLON.Material));
  50713. BABYLON.ShaderMaterial = ShaderMaterial;
  50714. })(BABYLON || (BABYLON = {}));
  50715. //# sourceMappingURL=babylon.shaderMaterial.js.map
  50716. var BABYLON;
  50717. (function (BABYLON) {
  50718. var GroundMesh = /** @class */ (function (_super) {
  50719. __extends(GroundMesh, _super);
  50720. function GroundMesh(name, scene) {
  50721. var _this = _super.call(this, name, scene) || this;
  50722. _this.generateOctree = false;
  50723. return _this;
  50724. }
  50725. GroundMesh.prototype.getClassName = function () {
  50726. return "GroundMesh";
  50727. };
  50728. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  50729. get: function () {
  50730. return Math.min(this._subdivisionsX, this._subdivisionsY);
  50731. },
  50732. enumerable: true,
  50733. configurable: true
  50734. });
  50735. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  50736. get: function () {
  50737. return this._subdivisionsX;
  50738. },
  50739. enumerable: true,
  50740. configurable: true
  50741. });
  50742. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  50743. get: function () {
  50744. return this._subdivisionsY;
  50745. },
  50746. enumerable: true,
  50747. configurable: true
  50748. });
  50749. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  50750. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  50751. this._subdivisionsX = chunksCount;
  50752. this._subdivisionsY = chunksCount;
  50753. this.subdivide(chunksCount);
  50754. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  50755. };
  50756. /**
  50757. * Returns a height (y) value in the Worl system :
  50758. * the ground altitude at the coordinates (x, z) expressed in the World system.
  50759. * Returns the ground y position if (x, z) are outside the ground surface.
  50760. */
  50761. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  50762. var world = this.getWorldMatrix();
  50763. var invMat = BABYLON.Tmp.Matrix[5];
  50764. world.invertToRef(invMat);
  50765. var tmpVect = BABYLON.Tmp.Vector3[8];
  50766. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  50767. x = tmpVect.x;
  50768. z = tmpVect.z;
  50769. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  50770. return this.position.y;
  50771. }
  50772. if (!this._heightQuads || this._heightQuads.length == 0) {
  50773. this._initHeightQuads();
  50774. this._computeHeightQuads();
  50775. }
  50776. var facet = this._getFacetAt(x, z);
  50777. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  50778. // return y in the World system
  50779. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  50780. return tmpVect.y;
  50781. };
  50782. /**
  50783. * Returns a normalized vector (Vector3) orthogonal to the ground
  50784. * at the ground coordinates (x, z) expressed in the World system.
  50785. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  50786. */
  50787. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  50788. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  50789. this.getNormalAtCoordinatesToRef(x, z, normal);
  50790. return normal;
  50791. };
  50792. /**
  50793. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  50794. * at the ground coordinates (x, z) expressed in the World system.
  50795. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  50796. * Returns the GroundMesh.
  50797. */
  50798. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  50799. var world = this.getWorldMatrix();
  50800. var tmpMat = BABYLON.Tmp.Matrix[5];
  50801. world.invertToRef(tmpMat);
  50802. var tmpVect = BABYLON.Tmp.Vector3[8];
  50803. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  50804. x = tmpVect.x;
  50805. z = tmpVect.z;
  50806. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  50807. return this;
  50808. }
  50809. if (!this._heightQuads || this._heightQuads.length == 0) {
  50810. this._initHeightQuads();
  50811. this._computeHeightQuads();
  50812. }
  50813. var facet = this._getFacetAt(x, z);
  50814. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  50815. return this;
  50816. };
  50817. /**
  50818. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  50819. * if the ground has been updated.
  50820. * This can be used in the render loop.
  50821. * Returns the GroundMesh.
  50822. */
  50823. GroundMesh.prototype.updateCoordinateHeights = function () {
  50824. if (!this._heightQuads || this._heightQuads.length == 0) {
  50825. this._initHeightQuads();
  50826. }
  50827. this._computeHeightQuads();
  50828. return this;
  50829. };
  50830. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  50831. GroundMesh.prototype._getFacetAt = function (x, z) {
  50832. // retrieve col and row from x, z coordinates in the ground local system
  50833. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  50834. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  50835. var quad = this._heightQuads[row * this._subdivisionsX + col];
  50836. var facet;
  50837. if (z < quad.slope.x * x + quad.slope.y) {
  50838. facet = quad.facet1;
  50839. }
  50840. else {
  50841. facet = quad.facet2;
  50842. }
  50843. return facet;
  50844. };
  50845. // Creates and populates the heightMap array with "facet" elements :
  50846. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  50847. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  50848. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  50849. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  50850. // Returns the GroundMesh.
  50851. GroundMesh.prototype._initHeightQuads = function () {
  50852. var subdivisionsX = this._subdivisionsX;
  50853. var subdivisionsY = this._subdivisionsY;
  50854. this._heightQuads = new Array();
  50855. for (var row = 0; row < subdivisionsY; row++) {
  50856. for (var col = 0; col < subdivisionsX; col++) {
  50857. 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) };
  50858. this._heightQuads[row * subdivisionsX + col] = quad;
  50859. }
  50860. }
  50861. return this;
  50862. };
  50863. // Compute each quad element values and update the the heightMap array :
  50864. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  50865. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  50866. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  50867. // Returns the GroundMesh.
  50868. GroundMesh.prototype._computeHeightQuads = function () {
  50869. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  50870. if (!positions) {
  50871. return this;
  50872. }
  50873. var v1 = BABYLON.Tmp.Vector3[3];
  50874. var v2 = BABYLON.Tmp.Vector3[2];
  50875. var v3 = BABYLON.Tmp.Vector3[1];
  50876. var v4 = BABYLON.Tmp.Vector3[0];
  50877. var v1v2 = BABYLON.Tmp.Vector3[4];
  50878. var v1v3 = BABYLON.Tmp.Vector3[5];
  50879. var v1v4 = BABYLON.Tmp.Vector3[6];
  50880. var norm1 = BABYLON.Tmp.Vector3[7];
  50881. var norm2 = BABYLON.Tmp.Vector3[8];
  50882. var i = 0;
  50883. var j = 0;
  50884. var k = 0;
  50885. var cd = 0; // 2D slope coefficient : z = cd * x + h
  50886. var h = 0;
  50887. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  50888. var d2 = 0;
  50889. var subdivisionsX = this._subdivisionsX;
  50890. var subdivisionsY = this._subdivisionsY;
  50891. for (var row = 0; row < subdivisionsY; row++) {
  50892. for (var col = 0; col < subdivisionsX; col++) {
  50893. i = col * 3;
  50894. j = row * (subdivisionsX + 1) * 3;
  50895. k = (row + 1) * (subdivisionsX + 1) * 3;
  50896. v1.x = positions[j + i];
  50897. v1.y = positions[j + i + 1];
  50898. v1.z = positions[j + i + 2];
  50899. v2.x = positions[j + i + 3];
  50900. v2.y = positions[j + i + 4];
  50901. v2.z = positions[j + i + 5];
  50902. v3.x = positions[k + i];
  50903. v3.y = positions[k + i + 1];
  50904. v3.z = positions[k + i + 2];
  50905. v4.x = positions[k + i + 3];
  50906. v4.y = positions[k + i + 4];
  50907. v4.z = positions[k + i + 5];
  50908. // 2D slope V1V4
  50909. cd = (v4.z - v1.z) / (v4.x - v1.x);
  50910. h = v1.z - cd * v1.x; // v1 belongs to the slope
  50911. // facet equations :
  50912. // we compute each facet normal vector
  50913. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  50914. // we compute the value d by applying the equation to v1 which belongs to the plane
  50915. // then we store the facet equation in a Vector4
  50916. v2.subtractToRef(v1, v1v2);
  50917. v3.subtractToRef(v1, v1v3);
  50918. v4.subtractToRef(v1, v1v4);
  50919. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  50920. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  50921. norm1.normalize();
  50922. norm2.normalize();
  50923. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  50924. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  50925. var quad = this._heightQuads[row * subdivisionsX + col];
  50926. quad.slope.copyFromFloats(cd, h);
  50927. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  50928. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  50929. }
  50930. }
  50931. return this;
  50932. };
  50933. GroundMesh.prototype.serialize = function (serializationObject) {
  50934. _super.prototype.serialize.call(this, serializationObject);
  50935. serializationObject.subdivisionsX = this._subdivisionsX;
  50936. serializationObject.subdivisionsY = this._subdivisionsY;
  50937. serializationObject.minX = this._minX;
  50938. serializationObject.maxX = this._maxX;
  50939. serializationObject.minZ = this._minZ;
  50940. serializationObject.maxZ = this._maxZ;
  50941. serializationObject.width = this._width;
  50942. serializationObject.height = this._height;
  50943. };
  50944. GroundMesh.Parse = function (parsedMesh, scene) {
  50945. var result = new GroundMesh(parsedMesh.name, scene);
  50946. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  50947. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  50948. result._minX = parsedMesh.minX;
  50949. result._maxX = parsedMesh.maxX;
  50950. result._minZ = parsedMesh.minZ;
  50951. result._maxZ = parsedMesh.maxZ;
  50952. result._width = parsedMesh.width;
  50953. result._height = parsedMesh.height;
  50954. return result;
  50955. };
  50956. return GroundMesh;
  50957. }(BABYLON.Mesh));
  50958. BABYLON.GroundMesh = GroundMesh;
  50959. })(BABYLON || (BABYLON = {}));
  50960. //# sourceMappingURL=babylon.groundMesh.js.map
  50961. var BABYLON;
  50962. (function (BABYLON) {
  50963. /**
  50964. * Creates an instance based on a source mesh.
  50965. */
  50966. var InstancedMesh = /** @class */ (function (_super) {
  50967. __extends(InstancedMesh, _super);
  50968. function InstancedMesh(name, source) {
  50969. var _this = _super.call(this, name, source.getScene()) || this;
  50970. source.instances.push(_this);
  50971. _this._sourceMesh = source;
  50972. _this.position.copyFrom(source.position);
  50973. _this.rotation.copyFrom(source.rotation);
  50974. _this.scaling.copyFrom(source.scaling);
  50975. if (source.rotationQuaternion) {
  50976. _this.rotationQuaternion = source.rotationQuaternion.clone();
  50977. }
  50978. _this.infiniteDistance = source.infiniteDistance;
  50979. _this.setPivotMatrix(source.getPivotMatrix());
  50980. _this.refreshBoundingInfo();
  50981. _this._syncSubMeshes();
  50982. return _this;
  50983. }
  50984. /**
  50985. * Returns the string "InstancedMesh".
  50986. */
  50987. InstancedMesh.prototype.getClassName = function () {
  50988. return "InstancedMesh";
  50989. };
  50990. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  50991. // Methods
  50992. get: function () {
  50993. return this._sourceMesh.receiveShadows;
  50994. },
  50995. enumerable: true,
  50996. configurable: true
  50997. });
  50998. Object.defineProperty(InstancedMesh.prototype, "material", {
  50999. get: function () {
  51000. return this._sourceMesh.material;
  51001. },
  51002. enumerable: true,
  51003. configurable: true
  51004. });
  51005. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  51006. get: function () {
  51007. return this._sourceMesh.visibility;
  51008. },
  51009. enumerable: true,
  51010. configurable: true
  51011. });
  51012. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  51013. get: function () {
  51014. return this._sourceMesh.skeleton;
  51015. },
  51016. enumerable: true,
  51017. configurable: true
  51018. });
  51019. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  51020. get: function () {
  51021. return this._sourceMesh.renderingGroupId;
  51022. },
  51023. enumerable: true,
  51024. configurable: true
  51025. });
  51026. /**
  51027. * Returns the total number of vertices (integer).
  51028. */
  51029. InstancedMesh.prototype.getTotalVertices = function () {
  51030. return this._sourceMesh.getTotalVertices();
  51031. };
  51032. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  51033. get: function () {
  51034. return this._sourceMesh;
  51035. },
  51036. enumerable: true,
  51037. configurable: true
  51038. });
  51039. /**
  51040. * Is this node ready to be used/rendered
  51041. * @return {boolean} is it ready
  51042. */
  51043. InstancedMesh.prototype.isReady = function () {
  51044. return this._sourceMesh.isReady(true);
  51045. };
  51046. /**
  51047. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  51048. */
  51049. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  51050. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  51051. };
  51052. /**
  51053. * Sets the vertex data of the mesh geometry for the requested `kind`.
  51054. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  51055. * The `data` are either a numeric array either a Float32Array.
  51056. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  51057. * 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).
  51058. * Note that a new underlying VertexBuffer object is created each call.
  51059. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  51060. *
  51061. * Possible `kind` values :
  51062. * - BABYLON.VertexBuffer.PositionKind
  51063. * - BABYLON.VertexBuffer.UVKind
  51064. * - BABYLON.VertexBuffer.UV2Kind
  51065. * - BABYLON.VertexBuffer.UV3Kind
  51066. * - BABYLON.VertexBuffer.UV4Kind
  51067. * - BABYLON.VertexBuffer.UV5Kind
  51068. * - BABYLON.VertexBuffer.UV6Kind
  51069. * - BABYLON.VertexBuffer.ColorKind
  51070. * - BABYLON.VertexBuffer.MatricesIndicesKind
  51071. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  51072. * - BABYLON.VertexBuffer.MatricesWeightsKind
  51073. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  51074. *
  51075. * Returns the Mesh.
  51076. */
  51077. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  51078. if (this.sourceMesh) {
  51079. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  51080. }
  51081. return this.sourceMesh;
  51082. };
  51083. /**
  51084. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  51085. * If the mesh has no geometry, it is simply returned as it is.
  51086. * The `data` are either a numeric array either a Float32Array.
  51087. * No new underlying VertexBuffer object is created.
  51088. * 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.
  51089. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  51090. *
  51091. * Possible `kind` values :
  51092. * - BABYLON.VertexBuffer.PositionKind
  51093. * - BABYLON.VertexBuffer.UVKind
  51094. * - BABYLON.VertexBuffer.UV2Kind
  51095. * - BABYLON.VertexBuffer.UV3Kind
  51096. * - BABYLON.VertexBuffer.UV4Kind
  51097. * - BABYLON.VertexBuffer.UV5Kind
  51098. * - BABYLON.VertexBuffer.UV6Kind
  51099. * - BABYLON.VertexBuffer.ColorKind
  51100. * - BABYLON.VertexBuffer.MatricesIndicesKind
  51101. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  51102. * - BABYLON.VertexBuffer.MatricesWeightsKind
  51103. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  51104. *
  51105. * Returns the Mesh.
  51106. */
  51107. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  51108. if (this.sourceMesh) {
  51109. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  51110. }
  51111. return this.sourceMesh;
  51112. };
  51113. /**
  51114. * Sets the mesh indices.
  51115. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  51116. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  51117. * This method creates a new index buffer each call.
  51118. * Returns the Mesh.
  51119. */
  51120. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  51121. if (totalVertices === void 0) { totalVertices = null; }
  51122. if (this.sourceMesh) {
  51123. this.sourceMesh.setIndices(indices, totalVertices);
  51124. }
  51125. return this.sourceMesh;
  51126. };
  51127. /**
  51128. * Boolean : True if the mesh owns the requested kind of data.
  51129. */
  51130. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  51131. return this._sourceMesh.isVerticesDataPresent(kind);
  51132. };
  51133. /**
  51134. * Returns an array of indices (IndicesArray).
  51135. */
  51136. InstancedMesh.prototype.getIndices = function () {
  51137. return this._sourceMesh.getIndices();
  51138. };
  51139. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  51140. get: function () {
  51141. return this._sourceMesh._positions;
  51142. },
  51143. enumerable: true,
  51144. configurable: true
  51145. });
  51146. /**
  51147. * Sets a new updated BoundingInfo to the mesh.
  51148. * Returns the mesh.
  51149. */
  51150. InstancedMesh.prototype.refreshBoundingInfo = function () {
  51151. var meshBB = this._sourceMesh.getBoundingInfo();
  51152. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  51153. this._updateBoundingInfo();
  51154. return this;
  51155. };
  51156. InstancedMesh.prototype._preActivate = function () {
  51157. if (this._currentLOD) {
  51158. this._currentLOD._preActivate();
  51159. }
  51160. return this;
  51161. };
  51162. InstancedMesh.prototype._activate = function (renderId) {
  51163. if (this._currentLOD) {
  51164. this._currentLOD._registerInstanceForRenderId(this, renderId);
  51165. }
  51166. return this;
  51167. };
  51168. /**
  51169. * Returns the current associated LOD AbstractMesh.
  51170. */
  51171. InstancedMesh.prototype.getLOD = function (camera) {
  51172. if (!camera) {
  51173. return this;
  51174. }
  51175. var boundingInfo = this.getBoundingInfo();
  51176. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  51177. if (this._currentLOD === this.sourceMesh) {
  51178. return this;
  51179. }
  51180. return this._currentLOD;
  51181. };
  51182. InstancedMesh.prototype._syncSubMeshes = function () {
  51183. this.releaseSubMeshes();
  51184. if (this._sourceMesh.subMeshes) {
  51185. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  51186. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  51187. }
  51188. }
  51189. return this;
  51190. };
  51191. InstancedMesh.prototype._generatePointsArray = function () {
  51192. return this._sourceMesh._generatePointsArray();
  51193. };
  51194. /**
  51195. * Creates a new InstancedMesh from the current mesh.
  51196. * - name (string) : the cloned mesh name
  51197. * - newParent (optional Node) : the optional Node to parent the clone to.
  51198. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  51199. *
  51200. * Returns the clone.
  51201. */
  51202. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  51203. var result = this._sourceMesh.createInstance(name);
  51204. // Deep copy
  51205. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  51206. // Bounding info
  51207. this.refreshBoundingInfo();
  51208. // Parent
  51209. if (newParent) {
  51210. result.parent = newParent;
  51211. }
  51212. if (!doNotCloneChildren) {
  51213. // Children
  51214. for (var index = 0; index < this.getScene().meshes.length; index++) {
  51215. var mesh = this.getScene().meshes[index];
  51216. if (mesh.parent === this) {
  51217. mesh.clone(mesh.name, result);
  51218. }
  51219. }
  51220. }
  51221. result.computeWorldMatrix(true);
  51222. return result;
  51223. };
  51224. /**
  51225. * Disposes the InstancedMesh.
  51226. * Returns nothing.
  51227. */
  51228. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  51229. // Remove from mesh
  51230. var index = this._sourceMesh.instances.indexOf(this);
  51231. this._sourceMesh.instances.splice(index, 1);
  51232. _super.prototype.dispose.call(this, doNotRecurse);
  51233. };
  51234. return InstancedMesh;
  51235. }(BABYLON.AbstractMesh));
  51236. BABYLON.InstancedMesh = InstancedMesh;
  51237. })(BABYLON || (BABYLON = {}));
  51238. //# sourceMappingURL=babylon.instancedMesh.js.map
  51239. var BABYLON;
  51240. (function (BABYLON) {
  51241. var LinesMesh = /** @class */ (function (_super) {
  51242. __extends(LinesMesh, _super);
  51243. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  51244. if (scene === void 0) { scene = null; }
  51245. if (parent === void 0) { parent = null; }
  51246. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  51247. _this.useVertexColor = useVertexColor;
  51248. _this.useVertexAlpha = useVertexAlpha;
  51249. _this.color = new BABYLON.Color3(1, 1, 1);
  51250. _this.alpha = 1;
  51251. if (source) {
  51252. _this.color = source.color.clone();
  51253. _this.alpha = source.alpha;
  51254. _this.useVertexColor = source.useVertexColor;
  51255. _this.useVertexAlpha = source.useVertexAlpha;
  51256. }
  51257. _this._intersectionThreshold = 0.1;
  51258. var defines = [];
  51259. var options = {
  51260. attributes: [BABYLON.VertexBuffer.PositionKind],
  51261. uniforms: ["world", "viewProjection"],
  51262. needAlphaBlending: true,
  51263. defines: defines
  51264. };
  51265. if (useVertexAlpha === false) {
  51266. options.needAlphaBlending = false;
  51267. }
  51268. if (!useVertexColor) {
  51269. options.uniforms.push("color");
  51270. }
  51271. else {
  51272. options.defines.push("#define VERTEXCOLOR");
  51273. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  51274. }
  51275. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  51276. return _this;
  51277. }
  51278. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  51279. /**
  51280. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  51281. * This margin is expressed in world space coordinates, so its value may vary.
  51282. * Default value is 0.1
  51283. * @returns the intersection Threshold value.
  51284. */
  51285. get: function () {
  51286. return this._intersectionThreshold;
  51287. },
  51288. /**
  51289. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  51290. * This margin is expressed in world space coordinates, so its value may vary.
  51291. * @param value the new threshold to apply
  51292. */
  51293. set: function (value) {
  51294. if (this._intersectionThreshold === value) {
  51295. return;
  51296. }
  51297. this._intersectionThreshold = value;
  51298. if (this.geometry) {
  51299. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  51300. }
  51301. },
  51302. enumerable: true,
  51303. configurable: true
  51304. });
  51305. /**
  51306. * Returns the string "LineMesh"
  51307. */
  51308. LinesMesh.prototype.getClassName = function () {
  51309. return "LinesMesh";
  51310. };
  51311. Object.defineProperty(LinesMesh.prototype, "material", {
  51312. get: function () {
  51313. return this._colorShader;
  51314. },
  51315. set: function (value) {
  51316. // Do nothing
  51317. },
  51318. enumerable: true,
  51319. configurable: true
  51320. });
  51321. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  51322. get: function () {
  51323. return false;
  51324. },
  51325. enumerable: true,
  51326. configurable: true
  51327. });
  51328. LinesMesh.prototype.createInstance = function (name) {
  51329. throw new Error("LinesMeshes do not support createInstance.");
  51330. };
  51331. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  51332. if (!this._geometry) {
  51333. return this;
  51334. }
  51335. // VBOs
  51336. this._geometry._bind(this._colorShader.getEffect());
  51337. // Color
  51338. if (!this.useVertexColor) {
  51339. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  51340. }
  51341. return this;
  51342. };
  51343. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  51344. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  51345. return this;
  51346. }
  51347. var engine = this.getScene().getEngine();
  51348. // Draw order
  51349. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  51350. return this;
  51351. };
  51352. LinesMesh.prototype.dispose = function (doNotRecurse) {
  51353. this._colorShader.dispose();
  51354. _super.prototype.dispose.call(this, doNotRecurse);
  51355. };
  51356. /**
  51357. * Returns a new LineMesh object cloned from the current one.
  51358. */
  51359. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  51360. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  51361. };
  51362. return LinesMesh;
  51363. }(BABYLON.Mesh));
  51364. BABYLON.LinesMesh = LinesMesh;
  51365. })(BABYLON || (BABYLON = {}));
  51366. //# sourceMappingURL=babylon.linesMesh.js.map
  51367. var BABYLON;
  51368. (function (BABYLON) {
  51369. var MeshBuilder = /** @class */ (function () {
  51370. function MeshBuilder() {
  51371. }
  51372. MeshBuilder.updateSideOrientation = function (orientation) {
  51373. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  51374. return BABYLON.Mesh.DOUBLESIDE;
  51375. }
  51376. if (orientation === undefined || orientation === null) {
  51377. return BABYLON.Mesh.FRONTSIDE;
  51378. }
  51379. return orientation;
  51380. };
  51381. /**
  51382. * Creates a box mesh.
  51383. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  51384. * The parameter `size` sets the size (float) of each box side (default 1).
  51385. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  51386. * 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).
  51387. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  51388. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51389. * 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).
  51390. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51391. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51392. */
  51393. MeshBuilder.CreateBox = function (name, options, scene) {
  51394. if (scene === void 0) { scene = null; }
  51395. var box = new BABYLON.Mesh(name, scene);
  51396. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51397. box._originalBuilderSideOrientation = options.sideOrientation;
  51398. var vertexData = BABYLON.VertexData.CreateBox(options);
  51399. vertexData.applyToMesh(box, options.updatable);
  51400. return box;
  51401. };
  51402. /**
  51403. * Creates a sphere mesh.
  51404. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  51405. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  51406. * 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`).
  51407. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  51408. * 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
  51409. * 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).
  51410. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51411. * 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).
  51412. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51413. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51414. */
  51415. MeshBuilder.CreateSphere = function (name, options, scene) {
  51416. var sphere = new BABYLON.Mesh(name, scene);
  51417. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51418. sphere._originalBuilderSideOrientation = options.sideOrientation;
  51419. var vertexData = BABYLON.VertexData.CreateSphere(options);
  51420. vertexData.applyToMesh(sphere, options.updatable);
  51421. return sphere;
  51422. };
  51423. /**
  51424. * Creates a plane polygonal mesh. By default, this is a disc.
  51425. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  51426. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  51427. * 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.
  51428. * 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
  51429. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51430. * 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).
  51431. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51432. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51433. */
  51434. MeshBuilder.CreateDisc = function (name, options, scene) {
  51435. if (scene === void 0) { scene = null; }
  51436. var disc = new BABYLON.Mesh(name, scene);
  51437. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51438. disc._originalBuilderSideOrientation = options.sideOrientation;
  51439. var vertexData = BABYLON.VertexData.CreateDisc(options);
  51440. vertexData.applyToMesh(disc, options.updatable);
  51441. return disc;
  51442. };
  51443. /**
  51444. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  51445. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  51446. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  51447. * 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`).
  51448. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  51449. * 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.
  51450. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51451. * 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).
  51452. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51453. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51454. */
  51455. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  51456. var sphere = new BABYLON.Mesh(name, scene);
  51457. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51458. sphere._originalBuilderSideOrientation = options.sideOrientation;
  51459. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  51460. vertexData.applyToMesh(sphere, options.updatable);
  51461. return sphere;
  51462. };
  51463. ;
  51464. /**
  51465. * Creates a ribbon mesh.
  51466. * 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.
  51467. *
  51468. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  51469. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  51470. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  51471. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  51472. * 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.
  51473. * 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.
  51474. * 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
  51475. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51476. * 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).
  51477. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51478. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  51479. * 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.
  51480. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  51481. * 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
  51482. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  51483. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  51484. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51485. */
  51486. MeshBuilder.CreateRibbon = function (name, options, scene) {
  51487. if (scene === void 0) { scene = null; }
  51488. var pathArray = options.pathArray;
  51489. var closeArray = options.closeArray;
  51490. var closePath = options.closePath;
  51491. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51492. var instance = options.instance;
  51493. var updatable = options.updatable;
  51494. if (instance) {
  51495. // positionFunction : ribbon case
  51496. // only pathArray and sideOrientation parameters are taken into account for positions update
  51497. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  51498. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  51499. var positionFunction = function (positions) {
  51500. var minlg = pathArray[0].length;
  51501. var i = 0;
  51502. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  51503. for (var si = 1; si <= ns; si++) {
  51504. for (var p = 0; p < pathArray.length; p++) {
  51505. var path = pathArray[p];
  51506. var l = path.length;
  51507. minlg = (minlg < l) ? minlg : l;
  51508. var j = 0;
  51509. while (j < minlg) {
  51510. positions[i] = path[j].x;
  51511. positions[i + 1] = path[j].y;
  51512. positions[i + 2] = path[j].z;
  51513. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  51514. BABYLON.Tmp.Vector3[0].x = path[j].x;
  51515. }
  51516. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  51517. BABYLON.Tmp.Vector3[1].x = path[j].x;
  51518. }
  51519. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  51520. BABYLON.Tmp.Vector3[0].y = path[j].y;
  51521. }
  51522. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  51523. BABYLON.Tmp.Vector3[1].y = path[j].y;
  51524. }
  51525. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  51526. BABYLON.Tmp.Vector3[0].z = path[j].z;
  51527. }
  51528. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  51529. BABYLON.Tmp.Vector3[1].z = path[j].z;
  51530. }
  51531. j++;
  51532. i += 3;
  51533. }
  51534. if (instance._closePath) {
  51535. positions[i] = path[0].x;
  51536. positions[i + 1] = path[0].y;
  51537. positions[i + 2] = path[0].z;
  51538. i += 3;
  51539. }
  51540. }
  51541. }
  51542. };
  51543. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  51544. positionFunction(positions);
  51545. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  51546. instance._boundingInfo.update(instance._worldMatrix);
  51547. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  51548. if (options.colors) {
  51549. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  51550. for (var c = 0; c < options.colors.length; c++) {
  51551. colors[c * 4] = options.colors[c].r;
  51552. colors[c * 4 + 1] = options.colors[c].g;
  51553. colors[c * 4 + 2] = options.colors[c].b;
  51554. colors[c * 4 + 3] = options.colors[c].a;
  51555. }
  51556. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  51557. }
  51558. if (options.uvs) {
  51559. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  51560. for (var i = 0; i < options.uvs.length; i++) {
  51561. uvs[i * 2] = options.uvs[i].x;
  51562. uvs[i * 2 + 1] = options.uvs[i].y;
  51563. }
  51564. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  51565. }
  51566. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  51567. var indices = instance.getIndices();
  51568. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  51569. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  51570. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  51571. if (instance._closePath) {
  51572. var indexFirst = 0;
  51573. var indexLast = 0;
  51574. for (var p = 0; p < pathArray.length; p++) {
  51575. indexFirst = instance._idx[p] * 3;
  51576. if (p + 1 < pathArray.length) {
  51577. indexLast = (instance._idx[p + 1] - 1) * 3;
  51578. }
  51579. else {
  51580. indexLast = normals.length - 3;
  51581. }
  51582. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  51583. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  51584. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  51585. normals[indexLast] = normals[indexFirst];
  51586. normals[indexLast + 1] = normals[indexFirst + 1];
  51587. normals[indexLast + 2] = normals[indexFirst + 2];
  51588. }
  51589. }
  51590. if (!(instance.areNormalsFrozen)) {
  51591. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  51592. }
  51593. }
  51594. return instance;
  51595. }
  51596. else {
  51597. var ribbon = new BABYLON.Mesh(name, scene);
  51598. ribbon._originalBuilderSideOrientation = sideOrientation;
  51599. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  51600. if (closePath) {
  51601. ribbon._idx = vertexData._idx;
  51602. }
  51603. ribbon._closePath = closePath;
  51604. ribbon._closeArray = closeArray;
  51605. vertexData.applyToMesh(ribbon, updatable);
  51606. return ribbon;
  51607. }
  51608. };
  51609. /**
  51610. * Creates a cylinder or a cone mesh.
  51611. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  51612. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  51613. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  51614. * 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.
  51615. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  51616. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  51617. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  51618. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  51619. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  51620. * 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).
  51621. * 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
  51622. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  51623. * 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
  51624. * 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.
  51625. * If `enclose` is false, a ring surface is one element.
  51626. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  51627. * 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
  51628. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51629. * 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).
  51630. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51631. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51632. */
  51633. MeshBuilder.CreateCylinder = function (name, options, scene) {
  51634. var cylinder = new BABYLON.Mesh(name, scene);
  51635. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51636. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  51637. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  51638. vertexData.applyToMesh(cylinder, options.updatable);
  51639. return cylinder;
  51640. };
  51641. /**
  51642. * Creates a torus mesh.
  51643. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  51644. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  51645. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  51646. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  51647. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51648. * 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).
  51649. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51650. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51651. */
  51652. MeshBuilder.CreateTorus = function (name, options, scene) {
  51653. var torus = new BABYLON.Mesh(name, scene);
  51654. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51655. torus._originalBuilderSideOrientation = options.sideOrientation;
  51656. var vertexData = BABYLON.VertexData.CreateTorus(options);
  51657. vertexData.applyToMesh(torus, options.updatable);
  51658. return torus;
  51659. };
  51660. /**
  51661. * Creates a torus knot mesh.
  51662. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  51663. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  51664. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  51665. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  51666. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  51667. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51668. * 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).
  51669. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51670. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51671. */
  51672. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  51673. var torusKnot = new BABYLON.Mesh(name, scene);
  51674. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51675. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  51676. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  51677. vertexData.applyToMesh(torusKnot, options.updatable);
  51678. return torusKnot;
  51679. };
  51680. /**
  51681. * Creates a line system mesh.
  51682. * A line system is a pool of many lines gathered in a single mesh.
  51683. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  51684. * 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.
  51685. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  51686. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  51687. * 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
  51688. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  51689. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  51690. * 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
  51691. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  51692. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51693. */
  51694. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  51695. var instance = options.instance;
  51696. var lines = options.lines;
  51697. var colors = options.colors;
  51698. if (instance) {
  51699. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  51700. var vertexColor;
  51701. var lineColors;
  51702. if (colors) {
  51703. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  51704. }
  51705. var i = 0;
  51706. var c = 0;
  51707. for (var l = 0; l < lines.length; l++) {
  51708. var points = lines[l];
  51709. for (var p = 0; p < points.length; p++) {
  51710. positions[i] = points[p].x;
  51711. positions[i + 1] = points[p].y;
  51712. positions[i + 2] = points[p].z;
  51713. if (colors && vertexColor) {
  51714. lineColors = colors[l];
  51715. vertexColor[c] = lineColors[p].r;
  51716. vertexColor[c + 1] = lineColors[p].g;
  51717. vertexColor[c + 2] = lineColors[p].b;
  51718. vertexColor[c + 3] = lineColors[p].a;
  51719. c += 4;
  51720. }
  51721. i += 3;
  51722. }
  51723. }
  51724. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  51725. if (colors && vertexColor) {
  51726. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  51727. }
  51728. return instance;
  51729. }
  51730. // line system creation
  51731. var useVertexColor = (colors) ? true : false;
  51732. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  51733. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  51734. vertexData.applyToMesh(lineSystem, options.updatable);
  51735. return lineSystem;
  51736. };
  51737. /**
  51738. * Creates a line mesh.
  51739. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  51740. * 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.
  51741. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  51742. * The parameter `points` is an array successive Vector3.
  51743. * 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
  51744. * The optional parameter `colors` is an array of successive Color4, one per line point.
  51745. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  51746. * When updating an instance, remember that only point positions can change, not the number of points.
  51747. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51748. */
  51749. MeshBuilder.CreateLines = function (name, options, scene) {
  51750. if (scene === void 0) { scene = null; }
  51751. var colors = (options.colors) ? [options.colors] : null;
  51752. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  51753. return lines;
  51754. };
  51755. /**
  51756. * Creates a dashed line mesh.
  51757. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  51758. * 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.
  51759. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  51760. * The parameter `points` is an array successive Vector3.
  51761. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  51762. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  51763. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  51764. * 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
  51765. * When updating an instance, remember that only point positions can change, not the number of points.
  51766. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51767. */
  51768. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  51769. if (scene === void 0) { scene = null; }
  51770. var points = options.points;
  51771. var instance = options.instance;
  51772. var gapSize = options.gapSize || 1;
  51773. var dashSize = options.dashSize || 3;
  51774. if (instance) {
  51775. var positionFunction = function (positions) {
  51776. var curvect = BABYLON.Vector3.Zero();
  51777. var nbSeg = positions.length / 6;
  51778. var lg = 0;
  51779. var nb = 0;
  51780. var shft = 0;
  51781. var dashshft = 0;
  51782. var curshft = 0;
  51783. var p = 0;
  51784. var i = 0;
  51785. var j = 0;
  51786. for (i = 0; i < points.length - 1; i++) {
  51787. points[i + 1].subtractToRef(points[i], curvect);
  51788. lg += curvect.length();
  51789. }
  51790. shft = lg / nbSeg;
  51791. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  51792. for (i = 0; i < points.length - 1; i++) {
  51793. points[i + 1].subtractToRef(points[i], curvect);
  51794. nb = Math.floor(curvect.length() / shft);
  51795. curvect.normalize();
  51796. j = 0;
  51797. while (j < nb && p < positions.length) {
  51798. curshft = shft * j;
  51799. positions[p] = points[i].x + curshft * curvect.x;
  51800. positions[p + 1] = points[i].y + curshft * curvect.y;
  51801. positions[p + 2] = points[i].z + curshft * curvect.z;
  51802. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  51803. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  51804. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  51805. p += 6;
  51806. j++;
  51807. }
  51808. }
  51809. while (p < positions.length) {
  51810. positions[p] = points[i].x;
  51811. positions[p + 1] = points[i].y;
  51812. positions[p + 2] = points[i].z;
  51813. p += 3;
  51814. }
  51815. };
  51816. instance.updateMeshPositions(positionFunction, false);
  51817. return instance;
  51818. }
  51819. // dashed lines creation
  51820. var dashedLines = new BABYLON.LinesMesh(name, scene);
  51821. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  51822. vertexData.applyToMesh(dashedLines, options.updatable);
  51823. dashedLines.dashSize = dashSize;
  51824. dashedLines.gapSize = gapSize;
  51825. return dashedLines;
  51826. };
  51827. /**
  51828. * Creates an extruded shape mesh.
  51829. * 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.
  51830. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  51831. *
  51832. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  51833. * 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
  51834. * extruded along the Z axis.
  51835. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  51836. * 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.
  51837. * The parameter `scale` (float, default 1) is the value to scale the shape.
  51838. * 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
  51839. * 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
  51840. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  51841. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51842. * 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).
  51843. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51844. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  51845. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51846. */
  51847. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  51848. if (scene === void 0) { scene = null; }
  51849. var path = options.path;
  51850. var shape = options.shape;
  51851. var scale = options.scale || 1;
  51852. var rotation = options.rotation || 0;
  51853. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  51854. var updatable = options.updatable;
  51855. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51856. var instance = options.instance || null;
  51857. var invertUV = options.invertUV || false;
  51858. 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);
  51859. };
  51860. /**
  51861. * Creates an custom extruded shape mesh.
  51862. * 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.
  51863. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  51864. *
  51865. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  51866. * 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
  51867. * extruded along the Z axis.
  51868. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  51869. * 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
  51870. * and the distance of this point from the begining of the path :
  51871. * ```javascript
  51872. * var rotationFunction = function(i, distance) {
  51873. * // do things
  51874. * return rotationValue; }
  51875. * ```
  51876. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  51877. * 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
  51878. * and the distance of this point from the begining of the path :
  51879. * ```javascript
  51880. * var scaleFunction = function(i, distance) {
  51881. * // do things
  51882. * return scaleValue;}
  51883. * ```
  51884. * It must returns a float value that will be the scale value applied to the shape on each path point.
  51885. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  51886. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  51887. * 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
  51888. * 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
  51889. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  51890. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51891. * 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).
  51892. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51893. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  51894. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51895. */
  51896. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  51897. var path = options.path;
  51898. var shape = options.shape;
  51899. var scaleFunction = options.scaleFunction || (function () { return 1; });
  51900. var rotationFunction = options.rotationFunction || (function () { return 0; });
  51901. var ribbonCloseArray = options.ribbonCloseArray || false;
  51902. var ribbonClosePath = options.ribbonClosePath || false;
  51903. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  51904. var updatable = options.updatable;
  51905. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51906. var instance = options.instance;
  51907. var invertUV = options.invertUV || false;
  51908. 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);
  51909. };
  51910. /**
  51911. * Creates lathe mesh.
  51912. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  51913. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  51914. *
  51915. * 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
  51916. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  51917. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  51918. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  51919. * 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.
  51920. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  51921. * 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
  51922. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51923. * 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).
  51924. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51925. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  51926. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51927. */
  51928. MeshBuilder.CreateLathe = function (name, options, scene) {
  51929. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  51930. var closed = (options.closed === undefined) ? true : options.closed;
  51931. var shape = options.shape;
  51932. var radius = options.radius || 1;
  51933. var tessellation = options.tessellation || 64;
  51934. var updatable = options.updatable;
  51935. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51936. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  51937. var pi2 = Math.PI * 2;
  51938. var paths = new Array();
  51939. var invertUV = options.invertUV || false;
  51940. var i = 0;
  51941. var p = 0;
  51942. var step = pi2 / tessellation * arc;
  51943. var rotated;
  51944. var path = new Array();
  51945. ;
  51946. for (i = 0; i <= tessellation; i++) {
  51947. var path = [];
  51948. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  51949. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  51950. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  51951. }
  51952. for (p = 0; p < shape.length; p++) {
  51953. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  51954. path.push(rotated);
  51955. }
  51956. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  51957. 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));
  51958. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  51959. }
  51960. paths.push(path);
  51961. }
  51962. // lathe ribbon
  51963. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  51964. return lathe;
  51965. };
  51966. /**
  51967. * Creates a plane mesh.
  51968. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  51969. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  51970. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  51971. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  51972. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51973. * 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).
  51974. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51975. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51976. */
  51977. MeshBuilder.CreatePlane = function (name, options, scene) {
  51978. var plane = new BABYLON.Mesh(name, scene);
  51979. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51980. plane._originalBuilderSideOrientation = options.sideOrientation;
  51981. var vertexData = BABYLON.VertexData.CreatePlane(options);
  51982. vertexData.applyToMesh(plane, options.updatable);
  51983. if (options.sourcePlane) {
  51984. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  51985. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  51986. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  51987. plane.rotate(vectorProduct, product);
  51988. }
  51989. return plane;
  51990. };
  51991. /**
  51992. * Creates a ground mesh.
  51993. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  51994. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  51995. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  51996. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51997. */
  51998. MeshBuilder.CreateGround = function (name, options, scene) {
  51999. var ground = new BABYLON.GroundMesh(name, scene);
  52000. ground._setReady(false);
  52001. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  52002. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  52003. ground._width = options.width || 1;
  52004. ground._height = options.height || 1;
  52005. ground._maxX = ground._width / 2;
  52006. ground._maxZ = ground._height / 2;
  52007. ground._minX = -ground._maxX;
  52008. ground._minZ = -ground._maxZ;
  52009. var vertexData = BABYLON.VertexData.CreateGround(options);
  52010. vertexData.applyToMesh(ground, options.updatable);
  52011. ground._setReady(true);
  52012. return ground;
  52013. };
  52014. /**
  52015. * Creates a tiled ground mesh.
  52016. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  52017. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  52018. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  52019. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  52020. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  52021. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  52022. * numbers of subdivisions on the ground width and height of each tile.
  52023. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52024. */
  52025. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  52026. var tiledGround = new BABYLON.Mesh(name, scene);
  52027. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  52028. vertexData.applyToMesh(tiledGround, options.updatable);
  52029. return tiledGround;
  52030. };
  52031. /**
  52032. * Creates a ground mesh from a height map.
  52033. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  52034. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  52035. * The parameter `url` sets the URL of the height map image resource.
  52036. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  52037. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  52038. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  52039. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  52040. * 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.
  52041. * 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).
  52042. * This function is passed the newly built mesh :
  52043. * ```javascript
  52044. * function(mesh) { // do things
  52045. * return; }
  52046. * ```
  52047. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52048. */
  52049. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  52050. var width = options.width || 10.0;
  52051. var height = options.height || 10.0;
  52052. var subdivisions = options.subdivisions || 1 | 0;
  52053. var minHeight = options.minHeight || 0.0;
  52054. var maxHeight = options.maxHeight || 1.0;
  52055. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  52056. var updatable = options.updatable;
  52057. var onReady = options.onReady;
  52058. var ground = new BABYLON.GroundMesh(name, scene);
  52059. ground._subdivisionsX = subdivisions;
  52060. ground._subdivisionsY = subdivisions;
  52061. ground._width = width;
  52062. ground._height = height;
  52063. ground._maxX = ground._width / 2.0;
  52064. ground._maxZ = ground._height / 2.0;
  52065. ground._minX = -ground._maxX;
  52066. ground._minZ = -ground._maxZ;
  52067. ground._setReady(false);
  52068. var onload = function (img) {
  52069. // Getting height map data
  52070. var canvas = document.createElement("canvas");
  52071. var context = canvas.getContext("2d");
  52072. if (!context) {
  52073. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  52074. }
  52075. if (scene.isDisposed) {
  52076. return;
  52077. }
  52078. var bufferWidth = img.width;
  52079. var bufferHeight = img.height;
  52080. canvas.width = bufferWidth;
  52081. canvas.height = bufferHeight;
  52082. context.drawImage(img, 0, 0);
  52083. // Create VertexData from map data
  52084. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  52085. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  52086. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  52087. width: width, height: height,
  52088. subdivisions: subdivisions,
  52089. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  52090. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  52091. });
  52092. vertexData.applyToMesh(ground, updatable);
  52093. ground._setReady(true);
  52094. //execute ready callback, if set
  52095. if (onReady) {
  52096. onReady(ground);
  52097. }
  52098. };
  52099. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  52100. return ground;
  52101. };
  52102. /**
  52103. * Creates a polygon mesh.
  52104. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  52105. * 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.
  52106. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52107. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52108. * 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).
  52109. * Remember you can only change the shape positions, not their number when updating a polygon.
  52110. */
  52111. MeshBuilder.CreatePolygon = function (name, options, scene) {
  52112. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52113. var shape = options.shape;
  52114. var holes = options.holes || [];
  52115. var depth = options.depth || 0;
  52116. var contours = [];
  52117. var hole = [];
  52118. for (var i = 0; i < shape.length; i++) {
  52119. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  52120. }
  52121. var epsilon = 0.00000001;
  52122. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  52123. contours.pop();
  52124. }
  52125. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  52126. for (var hNb = 0; hNb < holes.length; hNb++) {
  52127. hole = [];
  52128. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  52129. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  52130. }
  52131. polygonTriangulation.addHole(hole);
  52132. }
  52133. var polygon = polygonTriangulation.build(options.updatable, depth);
  52134. polygon._originalBuilderSideOrientation = options.sideOrientation;
  52135. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  52136. vertexData.applyToMesh(polygon, options.updatable);
  52137. return polygon;
  52138. };
  52139. ;
  52140. /**
  52141. * Creates an extruded polygon mesh, with depth in the Y direction.
  52142. * 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).
  52143. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  52144. */
  52145. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  52146. return MeshBuilder.CreatePolygon(name, options, scene);
  52147. };
  52148. ;
  52149. /**
  52150. * Creates a tube mesh.
  52151. * 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.
  52152. *
  52153. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  52154. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  52155. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  52156. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  52157. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  52158. * 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.
  52159. * It must return a radius value (positive float) :
  52160. * ```javascript
  52161. * var radiusFunction = function(i, distance) {
  52162. * // do things
  52163. * return radius; }
  52164. * ```
  52165. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  52166. * 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
  52167. * 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
  52168. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52169. * 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).
  52170. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52171. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  52172. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52173. */
  52174. MeshBuilder.CreateTube = function (name, options, scene) {
  52175. var path = options.path;
  52176. var instance = options.instance;
  52177. var radius = 1.0;
  52178. if (instance) {
  52179. radius = instance.radius;
  52180. }
  52181. if (options.radius !== undefined) {
  52182. radius = options.radius;
  52183. }
  52184. ;
  52185. var tessellation = options.tessellation || 64 | 0;
  52186. var radiusFunction = options.radiusFunction || null;
  52187. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  52188. var invertUV = options.invertUV || false;
  52189. var updatable = options.updatable;
  52190. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52191. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  52192. // tube geometry
  52193. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  52194. var tangents = path3D.getTangents();
  52195. var normals = path3D.getNormals();
  52196. var distances = path3D.getDistances();
  52197. var pi2 = Math.PI * 2;
  52198. var step = pi2 / tessellation * arc;
  52199. var returnRadius = function () { return radius; };
  52200. var radiusFunctionFinal = radiusFunction || returnRadius;
  52201. var circlePath;
  52202. var rad;
  52203. var normal;
  52204. var rotated;
  52205. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  52206. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  52207. for (var i = 0; i < path.length; i++) {
  52208. rad = radiusFunctionFinal(i, distances[i]); // current radius
  52209. circlePath = Array(); // current circle array
  52210. normal = normals[i]; // current normal
  52211. for (var t = 0; t < tessellation; t++) {
  52212. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  52213. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  52214. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  52215. rotated.scaleInPlace(rad).addInPlace(path[i]);
  52216. circlePath[t] = rotated;
  52217. }
  52218. circlePaths[index] = circlePath;
  52219. index++;
  52220. }
  52221. // cap
  52222. var capPath = function (nbPoints, pathIndex) {
  52223. var pointCap = Array();
  52224. for (var i = 0; i < nbPoints; i++) {
  52225. pointCap.push(path[pathIndex]);
  52226. }
  52227. return pointCap;
  52228. };
  52229. switch (cap) {
  52230. case BABYLON.Mesh.NO_CAP:
  52231. break;
  52232. case BABYLON.Mesh.CAP_START:
  52233. circlePaths[0] = capPath(tessellation, 0);
  52234. circlePaths[1] = circlePaths[2].slice(0);
  52235. break;
  52236. case BABYLON.Mesh.CAP_END:
  52237. circlePaths[index] = circlePaths[index - 1].slice(0);
  52238. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  52239. break;
  52240. case BABYLON.Mesh.CAP_ALL:
  52241. circlePaths[0] = capPath(tessellation, 0);
  52242. circlePaths[1] = circlePaths[2].slice(0);
  52243. circlePaths[index] = circlePaths[index - 1].slice(0);
  52244. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  52245. break;
  52246. default:
  52247. break;
  52248. }
  52249. return circlePaths;
  52250. };
  52251. var path3D;
  52252. var pathArray;
  52253. if (instance) {
  52254. var arc = options.arc || instance.arc;
  52255. path3D = (instance.path3D).update(path);
  52256. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  52257. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  52258. instance.path3D = path3D;
  52259. instance.pathArray = pathArray;
  52260. instance.arc = arc;
  52261. instance.radius = radius;
  52262. return instance;
  52263. }
  52264. // tube creation
  52265. path3D = new BABYLON.Path3D(path);
  52266. var newPathArray = new Array();
  52267. cap = (cap < 0 || cap > 3) ? 0 : cap;
  52268. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  52269. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  52270. tube.pathArray = pathArray;
  52271. tube.path3D = path3D;
  52272. tube.tessellation = tessellation;
  52273. tube.cap = cap;
  52274. tube.arc = options.arc;
  52275. tube.radius = radius;
  52276. return tube;
  52277. };
  52278. /**
  52279. * Creates a polyhedron mesh.
  52280. *
  52281. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  52282. * 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
  52283. * to choose the wanted type.
  52284. * The parameter `size` (positive float, default 1) sets the polygon size.
  52285. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  52286. * 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`.
  52287. * 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
  52288. * 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)`).
  52289. * 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
  52290. * 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.
  52291. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52292. * 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).
  52293. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52294. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52295. */
  52296. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  52297. var polyhedron = new BABYLON.Mesh(name, scene);
  52298. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52299. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  52300. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  52301. vertexData.applyToMesh(polyhedron, options.updatable);
  52302. return polyhedron;
  52303. };
  52304. /**
  52305. * Creates a decal mesh.
  52306. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  52307. * 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.
  52308. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  52309. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  52310. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  52311. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  52312. */
  52313. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  52314. var indices = sourceMesh.getIndices();
  52315. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  52316. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  52317. var position = options.position || BABYLON.Vector3.Zero();
  52318. var normal = options.normal || BABYLON.Vector3.Up();
  52319. var size = options.size || BABYLON.Vector3.One();
  52320. var angle = options.angle || 0;
  52321. // Getting correct rotation
  52322. if (!normal) {
  52323. var target = new BABYLON.Vector3(0, 0, 1);
  52324. var camera = sourceMesh.getScene().activeCamera;
  52325. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  52326. normal = camera.globalPosition.subtract(cameraWorldTarget);
  52327. }
  52328. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  52329. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  52330. var pitch = Math.atan2(normal.y, len);
  52331. // Matrix
  52332. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  52333. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  52334. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  52335. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  52336. var vertexData = new BABYLON.VertexData();
  52337. vertexData.indices = [];
  52338. vertexData.positions = [];
  52339. vertexData.normals = [];
  52340. vertexData.uvs = [];
  52341. var currentVertexDataIndex = 0;
  52342. var extractDecalVector3 = function (indexId) {
  52343. var result = new BABYLON.PositionNormalVertex();
  52344. if (!indices || !positions || !normals) {
  52345. return result;
  52346. }
  52347. var vertexId = indices[indexId];
  52348. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  52349. // Send vector to decal local world
  52350. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  52351. // Get normal
  52352. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  52353. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  52354. return result;
  52355. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  52356. var clip = function (vertices, axis) {
  52357. if (vertices.length === 0) {
  52358. return vertices;
  52359. }
  52360. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  52361. var clipVertices = function (v0, v1) {
  52362. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  52363. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  52364. };
  52365. var result = new Array();
  52366. for (var index = 0; index < vertices.length; index += 3) {
  52367. var v1Out;
  52368. var v2Out;
  52369. var v3Out;
  52370. var total = 0;
  52371. var nV1 = null;
  52372. var nV2 = null;
  52373. var nV3 = null;
  52374. var nV4 = null;
  52375. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  52376. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  52377. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  52378. v1Out = d1 > 0;
  52379. v2Out = d2 > 0;
  52380. v3Out = d3 > 0;
  52381. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  52382. switch (total) {
  52383. case 0:
  52384. result.push(vertices[index]);
  52385. result.push(vertices[index + 1]);
  52386. result.push(vertices[index + 2]);
  52387. break;
  52388. case 1:
  52389. if (v1Out) {
  52390. nV1 = vertices[index + 1];
  52391. nV2 = vertices[index + 2];
  52392. nV3 = clipVertices(vertices[index], nV1);
  52393. nV4 = clipVertices(vertices[index], nV2);
  52394. }
  52395. if (v2Out) {
  52396. nV1 = vertices[index];
  52397. nV2 = vertices[index + 2];
  52398. nV3 = clipVertices(vertices[index + 1], nV1);
  52399. nV4 = clipVertices(vertices[index + 1], nV2);
  52400. result.push(nV3);
  52401. result.push(nV2.clone());
  52402. result.push(nV1.clone());
  52403. result.push(nV2.clone());
  52404. result.push(nV3.clone());
  52405. result.push(nV4);
  52406. break;
  52407. }
  52408. if (v3Out) {
  52409. nV1 = vertices[index];
  52410. nV2 = vertices[index + 1];
  52411. nV3 = clipVertices(vertices[index + 2], nV1);
  52412. nV4 = clipVertices(vertices[index + 2], nV2);
  52413. }
  52414. if (nV1 && nV2 && nV3 && nV4) {
  52415. result.push(nV1.clone());
  52416. result.push(nV2.clone());
  52417. result.push(nV3);
  52418. result.push(nV4);
  52419. result.push(nV3.clone());
  52420. result.push(nV2.clone());
  52421. }
  52422. break;
  52423. case 2:
  52424. if (!v1Out) {
  52425. nV1 = vertices[index].clone();
  52426. nV2 = clipVertices(nV1, vertices[index + 1]);
  52427. nV3 = clipVertices(nV1, vertices[index + 2]);
  52428. result.push(nV1);
  52429. result.push(nV2);
  52430. result.push(nV3);
  52431. }
  52432. if (!v2Out) {
  52433. nV1 = vertices[index + 1].clone();
  52434. nV2 = clipVertices(nV1, vertices[index + 2]);
  52435. nV3 = clipVertices(nV1, vertices[index]);
  52436. result.push(nV1);
  52437. result.push(nV2);
  52438. result.push(nV3);
  52439. }
  52440. if (!v3Out) {
  52441. nV1 = vertices[index + 2].clone();
  52442. nV2 = clipVertices(nV1, vertices[index]);
  52443. nV3 = clipVertices(nV1, vertices[index + 1]);
  52444. result.push(nV1);
  52445. result.push(nV2);
  52446. result.push(nV3);
  52447. }
  52448. break;
  52449. case 3:
  52450. break;
  52451. }
  52452. }
  52453. return result;
  52454. };
  52455. for (var index = 0; index < indices.length; index += 3) {
  52456. var faceVertices = new Array();
  52457. faceVertices.push(extractDecalVector3(index));
  52458. faceVertices.push(extractDecalVector3(index + 1));
  52459. faceVertices.push(extractDecalVector3(index + 2));
  52460. // Clip
  52461. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  52462. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  52463. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  52464. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  52465. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  52466. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  52467. if (faceVertices.length === 0) {
  52468. continue;
  52469. }
  52470. // Add UVs and get back to world
  52471. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  52472. var vertex = faceVertices[vIndex];
  52473. //TODO check for Int32Array | Uint32Array | Uint16Array
  52474. vertexData.indices.push(currentVertexDataIndex);
  52475. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  52476. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  52477. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  52478. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  52479. currentVertexDataIndex++;
  52480. }
  52481. }
  52482. // Return mesh
  52483. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  52484. vertexData.applyToMesh(decal);
  52485. decal.position = position.clone();
  52486. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  52487. return decal;
  52488. };
  52489. // Privates
  52490. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  52491. // extrusion geometry
  52492. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  52493. var tangents = path3D.getTangents();
  52494. var normals = path3D.getNormals();
  52495. var binormals = path3D.getBinormals();
  52496. var distances = path3D.getDistances();
  52497. var angle = 0;
  52498. var returnScale = function () { return scale !== null ? scale : 1; };
  52499. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  52500. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  52501. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  52502. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  52503. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  52504. for (var i = 0; i < curve.length; i++) {
  52505. var shapePath = new Array();
  52506. var angleStep = rotate(i, distances[i]);
  52507. var scaleRatio = scl(i, distances[i]);
  52508. for (var p = 0; p < shape.length; p++) {
  52509. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  52510. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  52511. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  52512. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  52513. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  52514. shapePath[p] = rotated;
  52515. }
  52516. shapePaths[index] = shapePath;
  52517. angle += angleStep;
  52518. index++;
  52519. }
  52520. // cap
  52521. var capPath = function (shapePath) {
  52522. var pointCap = Array();
  52523. var barycenter = BABYLON.Vector3.Zero();
  52524. var i;
  52525. for (i = 0; i < shapePath.length; i++) {
  52526. barycenter.addInPlace(shapePath[i]);
  52527. }
  52528. barycenter.scaleInPlace(1.0 / shapePath.length);
  52529. for (i = 0; i < shapePath.length; i++) {
  52530. pointCap.push(barycenter);
  52531. }
  52532. return pointCap;
  52533. };
  52534. switch (cap) {
  52535. case BABYLON.Mesh.NO_CAP:
  52536. break;
  52537. case BABYLON.Mesh.CAP_START:
  52538. shapePaths[0] = capPath(shapePaths[2]);
  52539. shapePaths[1] = shapePaths[2];
  52540. break;
  52541. case BABYLON.Mesh.CAP_END:
  52542. shapePaths[index] = shapePaths[index - 1];
  52543. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  52544. break;
  52545. case BABYLON.Mesh.CAP_ALL:
  52546. shapePaths[0] = capPath(shapePaths[2]);
  52547. shapePaths[1] = shapePaths[2];
  52548. shapePaths[index] = shapePaths[index - 1];
  52549. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  52550. break;
  52551. default:
  52552. break;
  52553. }
  52554. return shapePaths;
  52555. };
  52556. var path3D;
  52557. var pathArray;
  52558. if (instance) {
  52559. path3D = (instance.path3D).update(curve);
  52560. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  52561. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  52562. return instance;
  52563. }
  52564. // extruded shape creation
  52565. path3D = new BABYLON.Path3D(curve);
  52566. var newShapePaths = new Array();
  52567. cap = (cap < 0 || cap > 3) ? 0 : cap;
  52568. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  52569. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  52570. extrudedGeneric.pathArray = pathArray;
  52571. extrudedGeneric.path3D = path3D;
  52572. extrudedGeneric.cap = cap;
  52573. return extrudedGeneric;
  52574. };
  52575. return MeshBuilder;
  52576. }());
  52577. BABYLON.MeshBuilder = MeshBuilder;
  52578. })(BABYLON || (BABYLON = {}));
  52579. //# sourceMappingURL=babylon.meshBuilder.js.map
  52580. var BABYLON;
  52581. (function (BABYLON) {
  52582. var AudioEngine = /** @class */ (function () {
  52583. function AudioEngine() {
  52584. this._audioContext = null;
  52585. this._audioContextInitialized = false;
  52586. this.canUseWebAudio = false;
  52587. this.WarnedWebAudioUnsupported = false;
  52588. this.unlocked = false;
  52589. this.isMP3supported = false;
  52590. this.isOGGsupported = false;
  52591. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  52592. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  52593. this.canUseWebAudio = true;
  52594. }
  52595. var audioElem = document.createElement('audio');
  52596. try {
  52597. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  52598. this.isMP3supported = true;
  52599. }
  52600. }
  52601. catch (e) {
  52602. // protect error during capability check.
  52603. }
  52604. try {
  52605. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  52606. this.isOGGsupported = true;
  52607. }
  52608. }
  52609. catch (e) {
  52610. // protect error during capability check.
  52611. }
  52612. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  52613. this._unlockiOSaudio();
  52614. }
  52615. else {
  52616. this.unlocked = true;
  52617. }
  52618. }
  52619. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  52620. get: function () {
  52621. if (!this._audioContextInitialized) {
  52622. this._initializeAudioContext();
  52623. }
  52624. return this._audioContext;
  52625. },
  52626. enumerable: true,
  52627. configurable: true
  52628. });
  52629. AudioEngine.prototype._unlockiOSaudio = function () {
  52630. var _this = this;
  52631. var unlockaudio = function () {
  52632. if (!_this.audioContext) {
  52633. return;
  52634. }
  52635. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  52636. var source = _this.audioContext.createBufferSource();
  52637. source.buffer = buffer;
  52638. source.connect(_this.audioContext.destination);
  52639. source.start(0);
  52640. setTimeout(function () {
  52641. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  52642. _this.unlocked = true;
  52643. window.removeEventListener('touchend', unlockaudio, false);
  52644. if (_this.onAudioUnlocked) {
  52645. _this.onAudioUnlocked();
  52646. }
  52647. }
  52648. }, 0);
  52649. };
  52650. window.addEventListener('touchend', unlockaudio, false);
  52651. };
  52652. AudioEngine.prototype._initializeAudioContext = function () {
  52653. try {
  52654. if (this.canUseWebAudio) {
  52655. this._audioContext = new AudioContext();
  52656. // create a global volume gain node
  52657. this.masterGain = this._audioContext.createGain();
  52658. this.masterGain.gain.value = 1;
  52659. this.masterGain.connect(this._audioContext.destination);
  52660. this._audioContextInitialized = true;
  52661. }
  52662. }
  52663. catch (e) {
  52664. this.canUseWebAudio = false;
  52665. BABYLON.Tools.Error("Web Audio: " + e.message);
  52666. }
  52667. };
  52668. AudioEngine.prototype.dispose = function () {
  52669. if (this.canUseWebAudio && this._audioContextInitialized) {
  52670. if (this._connectedAnalyser && this._audioContext) {
  52671. this._connectedAnalyser.stopDebugCanvas();
  52672. this._connectedAnalyser.dispose();
  52673. this.masterGain.disconnect();
  52674. this.masterGain.connect(this._audioContext.destination);
  52675. this._connectedAnalyser = null;
  52676. }
  52677. this.masterGain.gain.value = 1;
  52678. }
  52679. this.WarnedWebAudioUnsupported = false;
  52680. };
  52681. AudioEngine.prototype.getGlobalVolume = function () {
  52682. if (this.canUseWebAudio && this._audioContextInitialized) {
  52683. return this.masterGain.gain.value;
  52684. }
  52685. else {
  52686. return -1;
  52687. }
  52688. };
  52689. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  52690. if (this.canUseWebAudio && this._audioContextInitialized) {
  52691. this.masterGain.gain.value = newVolume;
  52692. }
  52693. };
  52694. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  52695. if (this._connectedAnalyser) {
  52696. this._connectedAnalyser.stopDebugCanvas();
  52697. }
  52698. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  52699. this._connectedAnalyser = analyser;
  52700. this.masterGain.disconnect();
  52701. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  52702. }
  52703. };
  52704. return AudioEngine;
  52705. }());
  52706. BABYLON.AudioEngine = AudioEngine;
  52707. })(BABYLON || (BABYLON = {}));
  52708. //# sourceMappingURL=babylon.audioEngine.js.map
  52709. var BABYLON;
  52710. (function (BABYLON) {
  52711. var Sound = /** @class */ (function () {
  52712. /**
  52713. * Create a sound and attach it to a scene
  52714. * @param name Name of your sound
  52715. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  52716. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  52717. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  52718. */
  52719. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  52720. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  52721. var _this = this;
  52722. this.autoplay = false;
  52723. this.loop = false;
  52724. this.useCustomAttenuation = false;
  52725. this.spatialSound = false;
  52726. this.refDistance = 1;
  52727. this.rolloffFactor = 1;
  52728. this.maxDistance = 100;
  52729. this.distanceModel = "linear";
  52730. this._panningModel = "equalpower";
  52731. this._playbackRate = 1;
  52732. this._streaming = false;
  52733. this._startTime = 0;
  52734. this._startOffset = 0;
  52735. this._position = BABYLON.Vector3.Zero();
  52736. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  52737. this._volume = 1;
  52738. this._isReadyToPlay = false;
  52739. this.isPlaying = false;
  52740. this.isPaused = false;
  52741. this._isDirectional = false;
  52742. // Used if you'd like to create a directional sound.
  52743. // If not set, the sound will be omnidirectional
  52744. this._coneInnerAngle = 360;
  52745. this._coneOuterAngle = 360;
  52746. this._coneOuterGain = 0;
  52747. this._isOutputConnected = false;
  52748. this._urlType = "Unknown";
  52749. this.name = name;
  52750. this._scene = scene;
  52751. this._readyToPlayCallback = readyToPlayCallback;
  52752. // Default custom attenuation function is a linear attenuation
  52753. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  52754. if (currentDistance < maxDistance) {
  52755. return currentVolume * (1 - currentDistance / maxDistance);
  52756. }
  52757. else {
  52758. return 0;
  52759. }
  52760. };
  52761. if (options) {
  52762. this.autoplay = options.autoplay || false;
  52763. this.loop = options.loop || false;
  52764. // if volume === 0, we need another way to check this option
  52765. if (options.volume !== undefined) {
  52766. this._volume = options.volume;
  52767. }
  52768. this.spatialSound = options.spatialSound || false;
  52769. this.maxDistance = options.maxDistance || 100;
  52770. this.useCustomAttenuation = options.useCustomAttenuation || false;
  52771. this.rolloffFactor = options.rolloffFactor || 1;
  52772. this.refDistance = options.refDistance || 1;
  52773. this.distanceModel = options.distanceModel || "linear";
  52774. this._playbackRate = options.playbackRate || 1;
  52775. this._streaming = options.streaming || false;
  52776. }
  52777. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  52778. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  52779. this._soundGain.gain.value = this._volume;
  52780. this._inputAudioNode = this._soundGain;
  52781. this._ouputAudioNode = this._soundGain;
  52782. if (this.spatialSound) {
  52783. this._createSpatialParameters();
  52784. }
  52785. this._scene.mainSoundTrack.AddSound(this);
  52786. var validParameter = true;
  52787. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  52788. if (urlOrArrayBuffer) {
  52789. if (typeof (urlOrArrayBuffer) === "string")
  52790. this._urlType = "String";
  52791. if (Array.isArray(urlOrArrayBuffer))
  52792. this._urlType = "Array";
  52793. if (urlOrArrayBuffer instanceof ArrayBuffer)
  52794. this._urlType = "ArrayBuffer";
  52795. var urls = [];
  52796. var codecSupportedFound = false;
  52797. switch (this._urlType) {
  52798. case "ArrayBuffer":
  52799. if (urlOrArrayBuffer.byteLength > 0) {
  52800. codecSupportedFound = true;
  52801. this._soundLoaded(urlOrArrayBuffer);
  52802. }
  52803. break;
  52804. case "String":
  52805. urls.push(urlOrArrayBuffer);
  52806. case "Array":
  52807. if (urls.length === 0)
  52808. urls = urlOrArrayBuffer;
  52809. // If we found a supported format, we load it immediately and stop the loop
  52810. for (var i = 0; i < urls.length; i++) {
  52811. var url = urls[i];
  52812. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  52813. codecSupportedFound = true;
  52814. }
  52815. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  52816. codecSupportedFound = true;
  52817. }
  52818. if (url.indexOf(".wav", url.length - 4) !== -1) {
  52819. codecSupportedFound = true;
  52820. }
  52821. if (url.indexOf("blob:") !== -1) {
  52822. codecSupportedFound = true;
  52823. }
  52824. if (codecSupportedFound) {
  52825. // Loading sound using XHR2
  52826. if (!this._streaming) {
  52827. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  52828. }
  52829. else {
  52830. this._htmlAudioElement = new Audio(url);
  52831. this._htmlAudioElement.controls = false;
  52832. this._htmlAudioElement.loop = this.loop;
  52833. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  52834. this._htmlAudioElement.preload = "auto";
  52835. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  52836. _this._isReadyToPlay = true;
  52837. if (_this.autoplay) {
  52838. _this.play();
  52839. }
  52840. if (_this._readyToPlayCallback) {
  52841. _this._readyToPlayCallback();
  52842. }
  52843. });
  52844. document.body.appendChild(this._htmlAudioElement);
  52845. }
  52846. break;
  52847. }
  52848. }
  52849. break;
  52850. default:
  52851. validParameter = false;
  52852. break;
  52853. }
  52854. if (!validParameter) {
  52855. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  52856. }
  52857. else {
  52858. if (!codecSupportedFound) {
  52859. this._isReadyToPlay = true;
  52860. // Simulating a ready to play event to avoid breaking code path
  52861. if (this._readyToPlayCallback) {
  52862. window.setTimeout(function () {
  52863. if (_this._readyToPlayCallback) {
  52864. _this._readyToPlayCallback();
  52865. }
  52866. }, 1000);
  52867. }
  52868. }
  52869. }
  52870. }
  52871. }
  52872. else {
  52873. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  52874. this._scene.mainSoundTrack.AddSound(this);
  52875. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  52876. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  52877. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  52878. }
  52879. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  52880. if (this._readyToPlayCallback) {
  52881. window.setTimeout(function () {
  52882. if (_this._readyToPlayCallback) {
  52883. _this._readyToPlayCallback();
  52884. }
  52885. }, 1000);
  52886. }
  52887. }
  52888. }
  52889. Sound.prototype.dispose = function () {
  52890. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  52891. if (this.isPlaying) {
  52892. this.stop();
  52893. }
  52894. this._isReadyToPlay = false;
  52895. if (this.soundTrackId === -1) {
  52896. this._scene.mainSoundTrack.RemoveSound(this);
  52897. }
  52898. else {
  52899. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  52900. }
  52901. if (this._soundGain) {
  52902. this._soundGain.disconnect();
  52903. this._soundGain = null;
  52904. }
  52905. if (this._soundPanner) {
  52906. this._soundPanner.disconnect();
  52907. this._soundPanner = null;
  52908. }
  52909. if (this._soundSource) {
  52910. this._soundSource.disconnect();
  52911. this._soundSource = null;
  52912. }
  52913. this._audioBuffer = null;
  52914. if (this._htmlAudioElement) {
  52915. this._htmlAudioElement.pause();
  52916. this._htmlAudioElement.src = "";
  52917. document.body.removeChild(this._htmlAudioElement);
  52918. }
  52919. if (this._connectedMesh && this._registerFunc) {
  52920. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  52921. this._connectedMesh = null;
  52922. }
  52923. }
  52924. };
  52925. Sound.prototype.isReady = function () {
  52926. return this._isReadyToPlay;
  52927. };
  52928. Sound.prototype._soundLoaded = function (audioData) {
  52929. var _this = this;
  52930. if (!BABYLON.Engine.audioEngine.audioContext) {
  52931. return;
  52932. }
  52933. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  52934. _this._audioBuffer = buffer;
  52935. _this._isReadyToPlay = true;
  52936. if (_this.autoplay) {
  52937. _this.play();
  52938. }
  52939. if (_this._readyToPlayCallback) {
  52940. _this._readyToPlayCallback();
  52941. }
  52942. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  52943. };
  52944. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  52945. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  52946. this._audioBuffer = audioBuffer;
  52947. this._isReadyToPlay = true;
  52948. }
  52949. };
  52950. Sound.prototype.updateOptions = function (options) {
  52951. if (options) {
  52952. this.loop = options.loop || this.loop;
  52953. this.maxDistance = options.maxDistance || this.maxDistance;
  52954. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  52955. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  52956. this.refDistance = options.refDistance || this.refDistance;
  52957. this.distanceModel = options.distanceModel || this.distanceModel;
  52958. this._playbackRate = options.playbackRate || this._playbackRate;
  52959. this._updateSpatialParameters();
  52960. if (this.isPlaying) {
  52961. if (this._streaming) {
  52962. this._htmlAudioElement.playbackRate = this._playbackRate;
  52963. }
  52964. else {
  52965. if (this._soundSource) {
  52966. this._soundSource.playbackRate.value = this._playbackRate;
  52967. }
  52968. }
  52969. }
  52970. }
  52971. };
  52972. Sound.prototype._createSpatialParameters = function () {
  52973. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  52974. if (this._scene.headphone) {
  52975. this._panningModel = "HRTF";
  52976. }
  52977. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  52978. this._updateSpatialParameters();
  52979. this._soundPanner.connect(this._ouputAudioNode);
  52980. this._inputAudioNode = this._soundPanner;
  52981. }
  52982. };
  52983. Sound.prototype._updateSpatialParameters = function () {
  52984. if (this.spatialSound && this._soundPanner) {
  52985. if (this.useCustomAttenuation) {
  52986. // Tricks to disable in a way embedded Web Audio attenuation
  52987. this._soundPanner.distanceModel = "linear";
  52988. this._soundPanner.maxDistance = Number.MAX_VALUE;
  52989. this._soundPanner.refDistance = 1;
  52990. this._soundPanner.rolloffFactor = 1;
  52991. this._soundPanner.panningModel = this._panningModel;
  52992. }
  52993. else {
  52994. this._soundPanner.distanceModel = this.distanceModel;
  52995. this._soundPanner.maxDistance = this.maxDistance;
  52996. this._soundPanner.refDistance = this.refDistance;
  52997. this._soundPanner.rolloffFactor = this.rolloffFactor;
  52998. this._soundPanner.panningModel = this._panningModel;
  52999. }
  53000. }
  53001. };
  53002. Sound.prototype.switchPanningModelToHRTF = function () {
  53003. this._panningModel = "HRTF";
  53004. this._switchPanningModel();
  53005. };
  53006. Sound.prototype.switchPanningModelToEqualPower = function () {
  53007. this._panningModel = "equalpower";
  53008. this._switchPanningModel();
  53009. };
  53010. Sound.prototype._switchPanningModel = function () {
  53011. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  53012. this._soundPanner.panningModel = this._panningModel;
  53013. }
  53014. };
  53015. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  53016. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  53017. if (this._isOutputConnected) {
  53018. this._ouputAudioNode.disconnect();
  53019. }
  53020. this._ouputAudioNode.connect(soundTrackAudioNode);
  53021. this._isOutputConnected = true;
  53022. }
  53023. };
  53024. /**
  53025. * Transform this sound into a directional source
  53026. * @param coneInnerAngle Size of the inner cone in degree
  53027. * @param coneOuterAngle Size of the outer cone in degree
  53028. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  53029. */
  53030. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  53031. if (coneOuterAngle < coneInnerAngle) {
  53032. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  53033. return;
  53034. }
  53035. this._coneInnerAngle = coneInnerAngle;
  53036. this._coneOuterAngle = coneOuterAngle;
  53037. this._coneOuterGain = coneOuterGain;
  53038. this._isDirectional = true;
  53039. if (this.isPlaying && this.loop) {
  53040. this.stop();
  53041. this.play();
  53042. }
  53043. };
  53044. Sound.prototype.setPosition = function (newPosition) {
  53045. this._position = newPosition;
  53046. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  53047. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  53048. }
  53049. };
  53050. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  53051. this._localDirection = newLocalDirection;
  53052. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  53053. this._updateDirection();
  53054. }
  53055. };
  53056. Sound.prototype._updateDirection = function () {
  53057. if (!this._connectedMesh || !this._soundPanner) {
  53058. return;
  53059. }
  53060. var mat = this._connectedMesh.getWorldMatrix();
  53061. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  53062. direction.normalize();
  53063. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  53064. };
  53065. Sound.prototype.updateDistanceFromListener = function () {
  53066. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  53067. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  53068. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  53069. }
  53070. };
  53071. Sound.prototype.setAttenuationFunction = function (callback) {
  53072. this._customAttenuationFunction = callback;
  53073. };
  53074. /**
  53075. * Play the sound
  53076. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  53077. * @param offset (optional) Start the sound setting it at a specific time
  53078. */
  53079. Sound.prototype.play = function (time, offset) {
  53080. var _this = this;
  53081. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  53082. try {
  53083. if (this._startOffset < 0) {
  53084. time = -this._startOffset;
  53085. this._startOffset = 0;
  53086. }
  53087. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  53088. if (!this._soundSource || !this._streamingSource) {
  53089. if (this.spatialSound && this._soundPanner) {
  53090. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  53091. if (this._isDirectional) {
  53092. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  53093. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  53094. this._soundPanner.coneOuterGain = this._coneOuterGain;
  53095. if (this._connectedMesh) {
  53096. this._updateDirection();
  53097. }
  53098. else {
  53099. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  53100. }
  53101. }
  53102. }
  53103. }
  53104. if (this._streaming) {
  53105. if (!this._streamingSource) {
  53106. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  53107. this._htmlAudioElement.onended = function () { _this._onended(); };
  53108. this._htmlAudioElement.playbackRate = this._playbackRate;
  53109. }
  53110. this._streamingSource.disconnect();
  53111. this._streamingSource.connect(this._inputAudioNode);
  53112. this._htmlAudioElement.play();
  53113. }
  53114. else {
  53115. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  53116. this._soundSource.buffer = this._audioBuffer;
  53117. this._soundSource.connect(this._inputAudioNode);
  53118. this._soundSource.loop = this.loop;
  53119. this._soundSource.playbackRate.value = this._playbackRate;
  53120. this._soundSource.onended = function () { _this._onended(); };
  53121. if (this._soundSource.buffer) {
  53122. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  53123. }
  53124. }
  53125. this._startTime = startTime;
  53126. this.isPlaying = true;
  53127. this.isPaused = false;
  53128. }
  53129. catch (ex) {
  53130. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  53131. }
  53132. }
  53133. };
  53134. Sound.prototype._onended = function () {
  53135. this.isPlaying = false;
  53136. if (this.onended) {
  53137. this.onended();
  53138. }
  53139. };
  53140. /**
  53141. * Stop the sound
  53142. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  53143. */
  53144. Sound.prototype.stop = function (time) {
  53145. if (this.isPlaying) {
  53146. if (this._streaming) {
  53147. this._htmlAudioElement.pause();
  53148. // Test needed for Firefox or it will generate an Invalid State Error
  53149. if (this._htmlAudioElement.currentTime > 0) {
  53150. this._htmlAudioElement.currentTime = 0;
  53151. }
  53152. }
  53153. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  53154. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  53155. this._soundSource.stop(stopTime);
  53156. this._soundSource.onended = function () { };
  53157. if (!this.isPaused) {
  53158. this._startOffset = 0;
  53159. }
  53160. }
  53161. this.isPlaying = false;
  53162. }
  53163. };
  53164. Sound.prototype.pause = function () {
  53165. if (this.isPlaying) {
  53166. this.isPaused = true;
  53167. if (this._streaming) {
  53168. this._htmlAudioElement.pause();
  53169. }
  53170. else if (BABYLON.Engine.audioEngine.audioContext) {
  53171. this.stop(0);
  53172. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  53173. }
  53174. }
  53175. };
  53176. Sound.prototype.setVolume = function (newVolume, time) {
  53177. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  53178. if (time && BABYLON.Engine.audioEngine.audioContext) {
  53179. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  53180. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  53181. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  53182. }
  53183. else {
  53184. this._soundGain.gain.value = newVolume;
  53185. }
  53186. }
  53187. this._volume = newVolume;
  53188. };
  53189. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  53190. this._playbackRate = newPlaybackRate;
  53191. if (this.isPlaying) {
  53192. if (this._streaming) {
  53193. this._htmlAudioElement.playbackRate = this._playbackRate;
  53194. }
  53195. else if (this._soundSource) {
  53196. this._soundSource.playbackRate.value = this._playbackRate;
  53197. }
  53198. }
  53199. };
  53200. Sound.prototype.getVolume = function () {
  53201. return this._volume;
  53202. };
  53203. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  53204. var _this = this;
  53205. if (this._connectedMesh && this._registerFunc) {
  53206. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  53207. this._registerFunc = null;
  53208. }
  53209. this._connectedMesh = meshToConnectTo;
  53210. if (!this.spatialSound) {
  53211. this.spatialSound = true;
  53212. this._createSpatialParameters();
  53213. if (this.isPlaying && this.loop) {
  53214. this.stop();
  53215. this.play();
  53216. }
  53217. }
  53218. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  53219. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  53220. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  53221. };
  53222. Sound.prototype.detachFromMesh = function () {
  53223. if (this._connectedMesh && this._registerFunc) {
  53224. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  53225. this._registerFunc = null;
  53226. this._connectedMesh = null;
  53227. }
  53228. };
  53229. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  53230. if (!node.getBoundingInfo) {
  53231. return;
  53232. }
  53233. var mesh = node;
  53234. var boundingInfo = mesh.getBoundingInfo();
  53235. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  53236. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  53237. this._updateDirection();
  53238. }
  53239. };
  53240. Sound.prototype.clone = function () {
  53241. var _this = this;
  53242. if (!this._streaming) {
  53243. var setBufferAndRun = function () {
  53244. if (_this._isReadyToPlay) {
  53245. clonedSound._audioBuffer = _this.getAudioBuffer();
  53246. clonedSound._isReadyToPlay = true;
  53247. if (clonedSound.autoplay) {
  53248. clonedSound.play();
  53249. }
  53250. }
  53251. else {
  53252. window.setTimeout(setBufferAndRun, 300);
  53253. }
  53254. };
  53255. var currentOptions = {
  53256. autoplay: this.autoplay, loop: this.loop,
  53257. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  53258. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  53259. refDistance: this.refDistance, distanceModel: this.distanceModel
  53260. };
  53261. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  53262. if (this.useCustomAttenuation) {
  53263. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  53264. }
  53265. clonedSound.setPosition(this._position);
  53266. clonedSound.setPlaybackRate(this._playbackRate);
  53267. setBufferAndRun();
  53268. return clonedSound;
  53269. }
  53270. else {
  53271. return null;
  53272. }
  53273. };
  53274. Sound.prototype.getAudioBuffer = function () {
  53275. return this._audioBuffer;
  53276. };
  53277. Sound.prototype.serialize = function () {
  53278. var serializationObject = {
  53279. name: this.name,
  53280. url: this.name,
  53281. autoplay: this.autoplay,
  53282. loop: this.loop,
  53283. volume: this._volume,
  53284. spatialSound: this.spatialSound,
  53285. maxDistance: this.maxDistance,
  53286. rolloffFactor: this.rolloffFactor,
  53287. refDistance: this.refDistance,
  53288. distanceModel: this.distanceModel,
  53289. playbackRate: this._playbackRate,
  53290. panningModel: this._panningModel,
  53291. soundTrackId: this.soundTrackId
  53292. };
  53293. if (this.spatialSound) {
  53294. if (this._connectedMesh)
  53295. serializationObject.connectedMeshId = this._connectedMesh.id;
  53296. serializationObject.position = this._position.asArray();
  53297. serializationObject.refDistance = this.refDistance;
  53298. serializationObject.distanceModel = this.distanceModel;
  53299. serializationObject.isDirectional = this._isDirectional;
  53300. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  53301. serializationObject.coneInnerAngle = this._coneInnerAngle;
  53302. serializationObject.coneOuterAngle = this._coneOuterAngle;
  53303. serializationObject.coneOuterGain = this._coneOuterGain;
  53304. }
  53305. return serializationObject;
  53306. };
  53307. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  53308. var soundName = parsedSound.name;
  53309. var soundUrl;
  53310. if (parsedSound.url) {
  53311. soundUrl = rootUrl + parsedSound.url;
  53312. }
  53313. else {
  53314. soundUrl = rootUrl + soundName;
  53315. }
  53316. var options = {
  53317. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  53318. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  53319. rolloffFactor: parsedSound.rolloffFactor,
  53320. refDistance: parsedSound.refDistance,
  53321. distanceModel: parsedSound.distanceModel,
  53322. playbackRate: parsedSound.playbackRate
  53323. };
  53324. var newSound;
  53325. if (!sourceSound) {
  53326. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  53327. scene._addPendingData(newSound);
  53328. }
  53329. else {
  53330. var setBufferAndRun = function () {
  53331. if (sourceSound._isReadyToPlay) {
  53332. newSound._audioBuffer = sourceSound.getAudioBuffer();
  53333. newSound._isReadyToPlay = true;
  53334. if (newSound.autoplay) {
  53335. newSound.play();
  53336. }
  53337. }
  53338. else {
  53339. window.setTimeout(setBufferAndRun, 300);
  53340. }
  53341. };
  53342. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  53343. setBufferAndRun();
  53344. }
  53345. if (parsedSound.position) {
  53346. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  53347. newSound.setPosition(soundPosition);
  53348. }
  53349. if (parsedSound.isDirectional) {
  53350. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  53351. if (parsedSound.localDirectionToMesh) {
  53352. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  53353. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  53354. }
  53355. }
  53356. if (parsedSound.connectedMeshId) {
  53357. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  53358. if (connectedMesh) {
  53359. newSound.attachToMesh(connectedMesh);
  53360. }
  53361. }
  53362. return newSound;
  53363. };
  53364. return Sound;
  53365. }());
  53366. BABYLON.Sound = Sound;
  53367. })(BABYLON || (BABYLON = {}));
  53368. //# sourceMappingURL=babylon.sound.js.map
  53369. var BABYLON;
  53370. (function (BABYLON) {
  53371. var SoundTrack = /** @class */ (function () {
  53372. function SoundTrack(scene, options) {
  53373. this.id = -1;
  53374. this._isMainTrack = false;
  53375. this._isInitialized = false;
  53376. this._scene = scene;
  53377. this.soundCollection = new Array();
  53378. this._options = options;
  53379. if (!this._isMainTrack) {
  53380. this._scene.soundTracks.push(this);
  53381. this.id = this._scene.soundTracks.length - 1;
  53382. }
  53383. }
  53384. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  53385. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  53386. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  53387. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  53388. if (this._options) {
  53389. if (this._options.volume) {
  53390. this._outputAudioNode.gain.value = this._options.volume;
  53391. }
  53392. if (this._options.mainTrack) {
  53393. this._isMainTrack = this._options.mainTrack;
  53394. }
  53395. }
  53396. this._isInitialized = true;
  53397. }
  53398. };
  53399. SoundTrack.prototype.dispose = function () {
  53400. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  53401. if (this._connectedAnalyser) {
  53402. this._connectedAnalyser.stopDebugCanvas();
  53403. }
  53404. while (this.soundCollection.length) {
  53405. this.soundCollection[0].dispose();
  53406. }
  53407. if (this._outputAudioNode) {
  53408. this._outputAudioNode.disconnect();
  53409. }
  53410. this._outputAudioNode = null;
  53411. }
  53412. };
  53413. SoundTrack.prototype.AddSound = function (sound) {
  53414. if (!this._isInitialized) {
  53415. this._initializeSoundTrackAudioGraph();
  53416. }
  53417. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  53418. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  53419. }
  53420. if (sound.soundTrackId) {
  53421. if (sound.soundTrackId === -1) {
  53422. this._scene.mainSoundTrack.RemoveSound(sound);
  53423. }
  53424. else {
  53425. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  53426. }
  53427. }
  53428. this.soundCollection.push(sound);
  53429. sound.soundTrackId = this.id;
  53430. };
  53431. SoundTrack.prototype.RemoveSound = function (sound) {
  53432. var index = this.soundCollection.indexOf(sound);
  53433. if (index !== -1) {
  53434. this.soundCollection.splice(index, 1);
  53435. }
  53436. };
  53437. SoundTrack.prototype.setVolume = function (newVolume) {
  53438. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  53439. this._outputAudioNode.gain.value = newVolume;
  53440. }
  53441. };
  53442. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  53443. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  53444. for (var i = 0; i < this.soundCollection.length; i++) {
  53445. this.soundCollection[i].switchPanningModelToHRTF();
  53446. }
  53447. }
  53448. };
  53449. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  53450. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  53451. for (var i = 0; i < this.soundCollection.length; i++) {
  53452. this.soundCollection[i].switchPanningModelToEqualPower();
  53453. }
  53454. }
  53455. };
  53456. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  53457. if (this._connectedAnalyser) {
  53458. this._connectedAnalyser.stopDebugCanvas();
  53459. }
  53460. this._connectedAnalyser = analyser;
  53461. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  53462. this._outputAudioNode.disconnect();
  53463. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  53464. }
  53465. };
  53466. return SoundTrack;
  53467. }());
  53468. BABYLON.SoundTrack = SoundTrack;
  53469. })(BABYLON || (BABYLON = {}));
  53470. //# sourceMappingURL=babylon.soundtrack.js.map
  53471. var BABYLON;
  53472. (function (BABYLON) {
  53473. var Analyser = /** @class */ (function () {
  53474. function Analyser(scene) {
  53475. this.SMOOTHING = 0.75;
  53476. this.FFT_SIZE = 512;
  53477. this.BARGRAPHAMPLITUDE = 256;
  53478. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  53479. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  53480. this._scene = scene;
  53481. this._audioEngine = BABYLON.Engine.audioEngine;
  53482. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  53483. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  53484. this._webAudioAnalyser.minDecibels = -140;
  53485. this._webAudioAnalyser.maxDecibels = 0;
  53486. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  53487. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  53488. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  53489. }
  53490. }
  53491. Analyser.prototype.getFrequencyBinCount = function () {
  53492. if (this._audioEngine.canUseWebAudio) {
  53493. return this._webAudioAnalyser.frequencyBinCount;
  53494. }
  53495. else {
  53496. return 0;
  53497. }
  53498. };
  53499. Analyser.prototype.getByteFrequencyData = function () {
  53500. if (this._audioEngine.canUseWebAudio) {
  53501. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  53502. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  53503. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  53504. }
  53505. return this._byteFreqs;
  53506. };
  53507. Analyser.prototype.getByteTimeDomainData = function () {
  53508. if (this._audioEngine.canUseWebAudio) {
  53509. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  53510. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  53511. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  53512. }
  53513. return this._byteTime;
  53514. };
  53515. Analyser.prototype.getFloatFrequencyData = function () {
  53516. if (this._audioEngine.canUseWebAudio) {
  53517. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  53518. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  53519. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  53520. }
  53521. return this._floatFreqs;
  53522. };
  53523. Analyser.prototype.drawDebugCanvas = function () {
  53524. var _this = this;
  53525. if (this._audioEngine.canUseWebAudio) {
  53526. if (!this._debugCanvas) {
  53527. this._debugCanvas = document.createElement("canvas");
  53528. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  53529. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  53530. this._debugCanvas.style.position = "absolute";
  53531. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  53532. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  53533. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  53534. document.body.appendChild(this._debugCanvas);
  53535. this._registerFunc = function () {
  53536. _this.drawDebugCanvas();
  53537. };
  53538. this._scene.registerBeforeRender(this._registerFunc);
  53539. }
  53540. if (this._registerFunc && this._debugCanvasContext) {
  53541. var workingArray = this.getByteFrequencyData();
  53542. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  53543. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  53544. // Draw the frequency domain chart.
  53545. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  53546. var value = workingArray[i];
  53547. var percent = value / this.BARGRAPHAMPLITUDE;
  53548. var height = this.DEBUGCANVASSIZE.height * percent;
  53549. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  53550. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  53551. var hue = i / this.getFrequencyBinCount() * 360;
  53552. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  53553. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  53554. }
  53555. }
  53556. }
  53557. };
  53558. Analyser.prototype.stopDebugCanvas = function () {
  53559. if (this._debugCanvas) {
  53560. if (this._registerFunc) {
  53561. this._scene.unregisterBeforeRender(this._registerFunc);
  53562. this._registerFunc = null;
  53563. }
  53564. document.body.removeChild(this._debugCanvas);
  53565. this._debugCanvas = null;
  53566. this._debugCanvasContext = null;
  53567. }
  53568. };
  53569. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  53570. if (this._audioEngine.canUseWebAudio) {
  53571. inputAudioNode.connect(this._webAudioAnalyser);
  53572. this._webAudioAnalyser.connect(outputAudioNode);
  53573. }
  53574. };
  53575. Analyser.prototype.dispose = function () {
  53576. if (this._audioEngine.canUseWebAudio) {
  53577. this._webAudioAnalyser.disconnect();
  53578. }
  53579. };
  53580. return Analyser;
  53581. }());
  53582. BABYLON.Analyser = Analyser;
  53583. })(BABYLON || (BABYLON = {}));
  53584. //# sourceMappingURL=babylon.analyser.js.map
  53585. var BABYLON;
  53586. (function (BABYLON) {
  53587. var CubeTexture = /** @class */ (function (_super) {
  53588. __extends(CubeTexture, _super);
  53589. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  53590. if (extensions === void 0) { extensions = null; }
  53591. if (noMipmap === void 0) { noMipmap = false; }
  53592. if (files === void 0) { files = null; }
  53593. if (onLoad === void 0) { onLoad = null; }
  53594. if (onError === void 0) { onError = null; }
  53595. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  53596. if (prefiltered === void 0) { prefiltered = false; }
  53597. if (forcedExtension === void 0) { forcedExtension = null; }
  53598. var _this = _super.call(this, scene) || this;
  53599. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  53600. _this.name = rootUrl;
  53601. _this.url = rootUrl;
  53602. _this._noMipmap = noMipmap;
  53603. _this.hasAlpha = false;
  53604. _this._format = format;
  53605. _this._prefiltered = prefiltered;
  53606. _this.isCube = true;
  53607. _this._textureMatrix = BABYLON.Matrix.Identity();
  53608. if (prefiltered) {
  53609. _this.gammaSpace = false;
  53610. }
  53611. if (!rootUrl && !files) {
  53612. return _this;
  53613. }
  53614. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  53615. var lastDot = rootUrl.lastIndexOf(".");
  53616. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  53617. var isDDS = (extension === ".dds");
  53618. if (!files) {
  53619. if (!isDDS && !extensions) {
  53620. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  53621. }
  53622. files = [];
  53623. if (extensions) {
  53624. for (var index = 0; index < extensions.length; index++) {
  53625. files.push(rootUrl + extensions[index]);
  53626. }
  53627. }
  53628. }
  53629. _this._files = files;
  53630. if (!_this._texture) {
  53631. if (!scene.useDelayedTextureLoading) {
  53632. if (prefiltered) {
  53633. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  53634. }
  53635. else {
  53636. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  53637. }
  53638. }
  53639. else {
  53640. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  53641. }
  53642. }
  53643. else if (onLoad) {
  53644. if (_this._texture.isReady) {
  53645. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  53646. }
  53647. else {
  53648. _this._texture.onLoadedObservable.add(onLoad);
  53649. }
  53650. }
  53651. return _this;
  53652. }
  53653. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  53654. return new CubeTexture("", scene, null, noMipmap, files);
  53655. };
  53656. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  53657. if (forcedExtension === void 0) { forcedExtension = null; }
  53658. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  53659. };
  53660. // Methods
  53661. CubeTexture.prototype.delayLoad = function () {
  53662. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  53663. return;
  53664. }
  53665. var scene = this.getScene();
  53666. if (!scene) {
  53667. return;
  53668. }
  53669. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  53670. this._texture = this._getFromCache(this.url, this._noMipmap);
  53671. if (!this._texture) {
  53672. if (this._prefiltered) {
  53673. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  53674. }
  53675. else {
  53676. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  53677. }
  53678. }
  53679. };
  53680. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  53681. return this._textureMatrix;
  53682. };
  53683. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  53684. this._textureMatrix = value;
  53685. };
  53686. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  53687. var texture = BABYLON.SerializationHelper.Parse(function () {
  53688. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  53689. }, parsedTexture, scene);
  53690. // Animations
  53691. if (parsedTexture.animations) {
  53692. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  53693. var parsedAnimation = parsedTexture.animations[animationIndex];
  53694. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  53695. }
  53696. }
  53697. return texture;
  53698. };
  53699. CubeTexture.prototype.clone = function () {
  53700. var _this = this;
  53701. return BABYLON.SerializationHelper.Clone(function () {
  53702. var scene = _this.getScene();
  53703. if (!scene) {
  53704. return _this;
  53705. }
  53706. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  53707. }, this);
  53708. };
  53709. return CubeTexture;
  53710. }(BABYLON.BaseTexture));
  53711. BABYLON.CubeTexture = CubeTexture;
  53712. })(BABYLON || (BABYLON = {}));
  53713. //# sourceMappingURL=babylon.cubeTexture.js.map
  53714. var BABYLON;
  53715. (function (BABYLON) {
  53716. var RenderTargetTexture = /** @class */ (function (_super) {
  53717. __extends(RenderTargetTexture, _super);
  53718. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  53719. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  53720. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  53721. if (isCube === void 0) { isCube = false; }
  53722. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53723. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  53724. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  53725. if (isMulti === void 0) { isMulti = false; }
  53726. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  53727. _this.isCube = isCube;
  53728. /**
  53729. * Use this list to define the list of mesh you want to render.
  53730. */
  53731. _this.renderList = new Array();
  53732. _this.renderParticles = true;
  53733. _this.renderSprites = false;
  53734. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  53735. _this.ignoreCameraViewport = false;
  53736. // Events
  53737. /**
  53738. * An event triggered when the texture is unbind.
  53739. * @type {BABYLON.Observable}
  53740. */
  53741. _this.onBeforeBindObservable = new BABYLON.Observable();
  53742. /**
  53743. * An event triggered when the texture is unbind.
  53744. * @type {BABYLON.Observable}
  53745. */
  53746. _this.onAfterUnbindObservable = new BABYLON.Observable();
  53747. /**
  53748. * An event triggered before rendering the texture
  53749. * @type {BABYLON.Observable}
  53750. */
  53751. _this.onBeforeRenderObservable = new BABYLON.Observable();
  53752. /**
  53753. * An event triggered after rendering the texture
  53754. * @type {BABYLON.Observable}
  53755. */
  53756. _this.onAfterRenderObservable = new BABYLON.Observable();
  53757. /**
  53758. * An event triggered after the texture clear
  53759. * @type {BABYLON.Observable}
  53760. */
  53761. _this.onClearObservable = new BABYLON.Observable();
  53762. _this._currentRefreshId = -1;
  53763. _this._refreshRate = 1;
  53764. _this._samples = 1;
  53765. scene = _this.getScene();
  53766. if (!scene) {
  53767. return _this;
  53768. }
  53769. _this._engine = scene.getEngine();
  53770. _this.name = name;
  53771. _this.isRenderTarget = true;
  53772. _this._initialSizeParameter = size;
  53773. _this._processSizeParameter(size);
  53774. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  53775. });
  53776. _this._generateMipMaps = generateMipMaps ? true : false;
  53777. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  53778. // Rendering groups
  53779. _this._renderingManager = new BABYLON.RenderingManager(scene);
  53780. if (isMulti) {
  53781. return _this;
  53782. }
  53783. _this._renderTargetOptions = {
  53784. generateMipMaps: generateMipMaps,
  53785. type: type,
  53786. samplingMode: samplingMode,
  53787. generateDepthBuffer: generateDepthBuffer,
  53788. generateStencilBuffer: generateStencilBuffer
  53789. };
  53790. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  53791. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53792. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53793. }
  53794. if (isCube) {
  53795. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  53796. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  53797. _this._textureMatrix = BABYLON.Matrix.Identity();
  53798. }
  53799. else {
  53800. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  53801. }
  53802. return _this;
  53803. }
  53804. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  53805. get: function () {
  53806. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  53807. },
  53808. enumerable: true,
  53809. configurable: true
  53810. });
  53811. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  53812. get: function () {
  53813. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  53814. },
  53815. enumerable: true,
  53816. configurable: true
  53817. });
  53818. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  53819. get: function () {
  53820. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  53821. },
  53822. enumerable: true,
  53823. configurable: true
  53824. });
  53825. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  53826. set: function (callback) {
  53827. if (this._onAfterUnbindObserver) {
  53828. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  53829. }
  53830. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  53831. },
  53832. enumerable: true,
  53833. configurable: true
  53834. });
  53835. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  53836. set: function (callback) {
  53837. if (this._onBeforeRenderObserver) {
  53838. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  53839. }
  53840. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  53841. },
  53842. enumerable: true,
  53843. configurable: true
  53844. });
  53845. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  53846. set: function (callback) {
  53847. if (this._onAfterRenderObserver) {
  53848. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  53849. }
  53850. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  53851. },
  53852. enumerable: true,
  53853. configurable: true
  53854. });
  53855. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  53856. set: function (callback) {
  53857. if (this._onClearObserver) {
  53858. this.onClearObservable.remove(this._onClearObserver);
  53859. }
  53860. this._onClearObserver = this.onClearObservable.add(callback);
  53861. },
  53862. enumerable: true,
  53863. configurable: true
  53864. });
  53865. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  53866. get: function () {
  53867. return this._renderTargetOptions;
  53868. },
  53869. enumerable: true,
  53870. configurable: true
  53871. });
  53872. RenderTargetTexture.prototype._onRatioRescale = function () {
  53873. if (this._sizeRatio) {
  53874. this.resize(this._initialSizeParameter);
  53875. }
  53876. };
  53877. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  53878. if (size.ratio) {
  53879. this._sizeRatio = size.ratio;
  53880. this._size = {
  53881. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  53882. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  53883. };
  53884. }
  53885. else {
  53886. this._size = size;
  53887. }
  53888. };
  53889. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  53890. get: function () {
  53891. return this._samples;
  53892. },
  53893. set: function (value) {
  53894. if (this._samples === value) {
  53895. return;
  53896. }
  53897. var scene = this.getScene();
  53898. if (!scene) {
  53899. return;
  53900. }
  53901. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  53902. },
  53903. enumerable: true,
  53904. configurable: true
  53905. });
  53906. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  53907. this._currentRefreshId = -1;
  53908. };
  53909. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  53910. get: function () {
  53911. return this._refreshRate;
  53912. },
  53913. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  53914. set: function (value) {
  53915. this._refreshRate = value;
  53916. this.resetRefreshCounter();
  53917. },
  53918. enumerable: true,
  53919. configurable: true
  53920. });
  53921. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  53922. if (!this._postProcessManager) {
  53923. var scene = this.getScene();
  53924. if (!scene) {
  53925. return;
  53926. }
  53927. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  53928. this._postProcesses = new Array();
  53929. }
  53930. this._postProcesses.push(postProcess);
  53931. this._postProcesses[0].autoClear = false;
  53932. };
  53933. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  53934. if (!this._postProcesses) {
  53935. return;
  53936. }
  53937. if (dispose) {
  53938. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  53939. var postProcess = _a[_i];
  53940. postProcess.dispose();
  53941. }
  53942. }
  53943. this._postProcesses = [];
  53944. };
  53945. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  53946. if (!this._postProcesses) {
  53947. return;
  53948. }
  53949. var index = this._postProcesses.indexOf(postProcess);
  53950. if (index === -1) {
  53951. return;
  53952. }
  53953. this._postProcesses.splice(index, 1);
  53954. if (this._postProcesses.length > 0) {
  53955. this._postProcesses[0].autoClear = false;
  53956. }
  53957. };
  53958. RenderTargetTexture.prototype._shouldRender = function () {
  53959. if (this._currentRefreshId === -1) {
  53960. this._currentRefreshId = 1;
  53961. return true;
  53962. }
  53963. if (this.refreshRate === this._currentRefreshId) {
  53964. this._currentRefreshId = 1;
  53965. return true;
  53966. }
  53967. this._currentRefreshId++;
  53968. return false;
  53969. };
  53970. RenderTargetTexture.prototype.getRenderSize = function () {
  53971. if (this._size.width) {
  53972. return this._size.width;
  53973. }
  53974. return this._size;
  53975. };
  53976. RenderTargetTexture.prototype.getRenderWidth = function () {
  53977. if (this._size.width) {
  53978. return this._size.width;
  53979. }
  53980. return this._size;
  53981. };
  53982. RenderTargetTexture.prototype.getRenderHeight = function () {
  53983. if (this._size.width) {
  53984. return this._size.height;
  53985. }
  53986. return this._size;
  53987. };
  53988. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  53989. get: function () {
  53990. return true;
  53991. },
  53992. enumerable: true,
  53993. configurable: true
  53994. });
  53995. RenderTargetTexture.prototype.scale = function (ratio) {
  53996. var newSize = this.getRenderSize() * ratio;
  53997. this.resize(newSize);
  53998. };
  53999. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  54000. if (this.isCube) {
  54001. return this._textureMatrix;
  54002. }
  54003. return _super.prototype.getReflectionTextureMatrix.call(this);
  54004. };
  54005. RenderTargetTexture.prototype.resize = function (size) {
  54006. this.releaseInternalTexture();
  54007. var scene = this.getScene();
  54008. if (!scene) {
  54009. return;
  54010. }
  54011. this._processSizeParameter(size);
  54012. if (this.isCube) {
  54013. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  54014. }
  54015. else {
  54016. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  54017. }
  54018. };
  54019. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  54020. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  54021. if (dumpForDebug === void 0) { dumpForDebug = false; }
  54022. var scene = this.getScene();
  54023. if (!scene) {
  54024. return;
  54025. }
  54026. var engine = scene.getEngine();
  54027. if (this.useCameraPostProcesses !== undefined) {
  54028. useCameraPostProcess = this.useCameraPostProcesses;
  54029. }
  54030. if (this._waitingRenderList) {
  54031. this.renderList = [];
  54032. for (var index = 0; index < this._waitingRenderList.length; index++) {
  54033. var id = this._waitingRenderList[index];
  54034. var mesh_1 = scene.getMeshByID(id);
  54035. if (mesh_1) {
  54036. this.renderList.push(mesh_1);
  54037. }
  54038. }
  54039. delete this._waitingRenderList;
  54040. }
  54041. // Is predicate defined?
  54042. if (this.renderListPredicate) {
  54043. if (this.renderList) {
  54044. this.renderList.splice(0); // Clear previous renderList
  54045. }
  54046. else {
  54047. this.renderList = [];
  54048. }
  54049. var scene = this.getScene();
  54050. if (!scene) {
  54051. return;
  54052. }
  54053. var sceneMeshes = scene.meshes;
  54054. for (var index = 0; index < sceneMeshes.length; index++) {
  54055. var mesh = sceneMeshes[index];
  54056. if (this.renderListPredicate(mesh)) {
  54057. this.renderList.push(mesh);
  54058. }
  54059. }
  54060. }
  54061. this.onBeforeBindObservable.notifyObservers(this);
  54062. // Set custom projection.
  54063. // Needs to be before binding to prevent changing the aspect ratio.
  54064. var camera;
  54065. if (this.activeCamera) {
  54066. camera = this.activeCamera;
  54067. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  54068. if (this.activeCamera !== scene.activeCamera) {
  54069. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  54070. }
  54071. }
  54072. else {
  54073. camera = scene.activeCamera;
  54074. if (camera) {
  54075. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  54076. }
  54077. }
  54078. // Prepare renderingManager
  54079. this._renderingManager.reset();
  54080. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  54081. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  54082. var sceneRenderId = scene.getRenderId();
  54083. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  54084. var mesh = currentRenderList[meshIndex];
  54085. if (mesh) {
  54086. if (!mesh.isReady()) {
  54087. // Reset _currentRefreshId
  54088. this.resetRefreshCounter();
  54089. continue;
  54090. }
  54091. mesh._preActivateForIntermediateRendering(sceneRenderId);
  54092. var isMasked = void 0;
  54093. if (!this.renderList && camera) {
  54094. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  54095. }
  54096. else {
  54097. isMasked = false;
  54098. }
  54099. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  54100. mesh._activate(sceneRenderId);
  54101. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  54102. var subMesh = mesh.subMeshes[subIndex];
  54103. scene._activeIndices.addCount(subMesh.indexCount, false);
  54104. this._renderingManager.dispatch(subMesh, mesh);
  54105. }
  54106. }
  54107. }
  54108. }
  54109. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  54110. var particleSystem = scene.particleSystems[particleIndex];
  54111. var emitter = particleSystem.emitter;
  54112. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  54113. continue;
  54114. }
  54115. if (currentRenderList.indexOf(emitter) >= 0) {
  54116. this._renderingManager.dispatchParticles(particleSystem);
  54117. }
  54118. }
  54119. if (this.isCube) {
  54120. for (var face = 0; face < 6; face++) {
  54121. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  54122. scene.incrementRenderId();
  54123. scene.resetCachedMaterial();
  54124. }
  54125. }
  54126. else {
  54127. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  54128. }
  54129. this.onAfterUnbindObservable.notifyObservers(this);
  54130. if (scene.activeCamera) {
  54131. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  54132. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  54133. }
  54134. engine.setViewport(scene.activeCamera.viewport);
  54135. }
  54136. scene.resetCachedMaterial();
  54137. };
  54138. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  54139. var minimum = 128;
  54140. var x = renderDimension * scale;
  54141. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  54142. // Ensure we don't exceed the render dimension (while staying POT)
  54143. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  54144. };
  54145. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  54146. var _this = this;
  54147. if (!this._texture) {
  54148. return;
  54149. }
  54150. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  54151. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  54152. });
  54153. };
  54154. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  54155. var scene = this.getScene();
  54156. if (!scene) {
  54157. return;
  54158. }
  54159. var engine = scene.getEngine();
  54160. if (!this._texture) {
  54161. return;
  54162. }
  54163. // Bind
  54164. if (this._postProcessManager) {
  54165. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  54166. }
  54167. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  54168. if (this._texture) {
  54169. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  54170. }
  54171. }
  54172. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  54173. // Clear
  54174. if (this.onClearObservable.hasObservers()) {
  54175. this.onClearObservable.notifyObservers(engine);
  54176. }
  54177. else {
  54178. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  54179. }
  54180. if (!this._doNotChangeAspectRatio) {
  54181. scene.updateTransformMatrix(true);
  54182. }
  54183. // Render
  54184. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  54185. if (this._postProcessManager) {
  54186. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  54187. }
  54188. else if (useCameraPostProcess) {
  54189. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  54190. }
  54191. if (!this._doNotChangeAspectRatio) {
  54192. scene.updateTransformMatrix(true);
  54193. }
  54194. // Dump ?
  54195. if (dumpForDebug) {
  54196. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  54197. }
  54198. // Unbind
  54199. if (!this.isCube || faceIndex === 5) {
  54200. if (this.isCube) {
  54201. if (faceIndex === 5) {
  54202. engine.generateMipMapsForCubemap(this._texture);
  54203. }
  54204. }
  54205. this.unbindFrameBuffer(engine, faceIndex);
  54206. }
  54207. else {
  54208. this.onAfterRenderObservable.notifyObservers(faceIndex);
  54209. }
  54210. };
  54211. /**
  54212. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  54213. * This allowed control for front to back rendering or reversly depending of the special needs.
  54214. *
  54215. * @param renderingGroupId The rendering group id corresponding to its index
  54216. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  54217. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  54218. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  54219. */
  54220. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  54221. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  54222. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  54223. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  54224. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  54225. };
  54226. /**
  54227. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  54228. *
  54229. * @param renderingGroupId The rendering group id corresponding to its index
  54230. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  54231. */
  54232. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  54233. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  54234. };
  54235. RenderTargetTexture.prototype.clone = function () {
  54236. var textureSize = this.getSize();
  54237. 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);
  54238. // Base texture
  54239. newTexture.hasAlpha = this.hasAlpha;
  54240. newTexture.level = this.level;
  54241. // RenderTarget Texture
  54242. newTexture.coordinatesMode = this.coordinatesMode;
  54243. if (this.renderList) {
  54244. newTexture.renderList = this.renderList.slice(0);
  54245. }
  54246. return newTexture;
  54247. };
  54248. RenderTargetTexture.prototype.serialize = function () {
  54249. if (!this.name) {
  54250. return null;
  54251. }
  54252. var serializationObject = _super.prototype.serialize.call(this);
  54253. serializationObject.renderTargetSize = this.getRenderSize();
  54254. serializationObject.renderList = [];
  54255. if (this.renderList) {
  54256. for (var index = 0; index < this.renderList.length; index++) {
  54257. serializationObject.renderList.push(this.renderList[index].id);
  54258. }
  54259. }
  54260. return serializationObject;
  54261. };
  54262. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  54263. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  54264. var objBuffer = this.getInternalTexture();
  54265. var scene = this.getScene();
  54266. if (objBuffer && scene) {
  54267. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  54268. }
  54269. };
  54270. RenderTargetTexture.prototype.dispose = function () {
  54271. if (this._postProcessManager) {
  54272. this._postProcessManager.dispose();
  54273. this._postProcessManager = null;
  54274. }
  54275. this.clearPostProcesses(true);
  54276. if (this._resizeObserver) {
  54277. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  54278. this._resizeObserver = null;
  54279. }
  54280. this.renderList = null;
  54281. // Remove from custom render targets
  54282. var scene = this.getScene();
  54283. if (!scene) {
  54284. return;
  54285. }
  54286. var index = scene.customRenderTargets.indexOf(this);
  54287. if (index >= 0) {
  54288. scene.customRenderTargets.splice(index, 1);
  54289. }
  54290. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  54291. var camera = _a[_i];
  54292. index = camera.customRenderTargets.indexOf(this);
  54293. if (index >= 0) {
  54294. camera.customRenderTargets.splice(index, 1);
  54295. }
  54296. }
  54297. _super.prototype.dispose.call(this);
  54298. };
  54299. RenderTargetTexture.prototype._rebuild = function () {
  54300. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  54301. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  54302. }
  54303. if (this._postProcessManager) {
  54304. this._postProcessManager._rebuild();
  54305. }
  54306. };
  54307. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  54308. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  54309. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  54310. return RenderTargetTexture;
  54311. }(BABYLON.Texture));
  54312. BABYLON.RenderTargetTexture = RenderTargetTexture;
  54313. })(BABYLON || (BABYLON = {}));
  54314. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  54315. var BABYLON;
  54316. (function (BABYLON) {
  54317. ;
  54318. var MultiRenderTarget = /** @class */ (function (_super) {
  54319. __extends(MultiRenderTarget, _super);
  54320. function MultiRenderTarget(name, size, count, scene, options) {
  54321. var _this = this;
  54322. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  54323. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  54324. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  54325. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  54326. _this._engine = scene.getEngine();
  54327. if (!_this.isSupported) {
  54328. _this.dispose();
  54329. return;
  54330. }
  54331. var types = [];
  54332. var samplingModes = [];
  54333. for (var i = 0; i < count; i++) {
  54334. if (options && options.types && options.types[i] !== undefined) {
  54335. types.push(options.types[i]);
  54336. }
  54337. else {
  54338. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  54339. }
  54340. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  54341. samplingModes.push(options.samplingModes[i]);
  54342. }
  54343. else {
  54344. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  54345. }
  54346. }
  54347. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  54348. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  54349. _this._size = size;
  54350. _this._multiRenderTargetOptions = {
  54351. samplingModes: samplingModes,
  54352. generateMipMaps: generateMipMaps,
  54353. generateDepthBuffer: generateDepthBuffer,
  54354. generateStencilBuffer: generateStencilBuffer,
  54355. generateDepthTexture: generateDepthTexture,
  54356. types: types,
  54357. textureCount: count
  54358. };
  54359. _this._createInternalTextures();
  54360. _this._createTextures();
  54361. return _this;
  54362. }
  54363. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  54364. get: function () {
  54365. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  54366. },
  54367. enumerable: true,
  54368. configurable: true
  54369. });
  54370. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  54371. get: function () {
  54372. return this._textures;
  54373. },
  54374. enumerable: true,
  54375. configurable: true
  54376. });
  54377. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  54378. get: function () {
  54379. return this._textures[this._textures.length - 1];
  54380. },
  54381. enumerable: true,
  54382. configurable: true
  54383. });
  54384. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  54385. set: function (wrap) {
  54386. if (this._textures) {
  54387. for (var i = 0; i < this._textures.length; i++) {
  54388. this._textures[i].wrapU = wrap;
  54389. }
  54390. }
  54391. },
  54392. enumerable: true,
  54393. configurable: true
  54394. });
  54395. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  54396. set: function (wrap) {
  54397. if (this._textures) {
  54398. for (var i = 0; i < this._textures.length; i++) {
  54399. this._textures[i].wrapV = wrap;
  54400. }
  54401. }
  54402. },
  54403. enumerable: true,
  54404. configurable: true
  54405. });
  54406. MultiRenderTarget.prototype._rebuild = function () {
  54407. this.releaseInternalTextures();
  54408. this._createInternalTextures();
  54409. for (var i = 0; i < this._internalTextures.length; i++) {
  54410. var texture = this._textures[i];
  54411. texture._texture = this._internalTextures[i];
  54412. }
  54413. // Keeps references to frame buffer and stencil/depth buffer
  54414. this._texture = this._internalTextures[0];
  54415. };
  54416. MultiRenderTarget.prototype._createInternalTextures = function () {
  54417. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  54418. };
  54419. MultiRenderTarget.prototype._createTextures = function () {
  54420. this._textures = [];
  54421. for (var i = 0; i < this._internalTextures.length; i++) {
  54422. var texture = new BABYLON.Texture(null, this.getScene());
  54423. texture._texture = this._internalTextures[i];
  54424. this._textures.push(texture);
  54425. }
  54426. // Keeps references to frame buffer and stencil/depth buffer
  54427. this._texture = this._internalTextures[0];
  54428. };
  54429. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  54430. get: function () {
  54431. return this._samples;
  54432. },
  54433. set: function (value) {
  54434. if (this._samples === value) {
  54435. return;
  54436. }
  54437. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  54438. },
  54439. enumerable: true,
  54440. configurable: true
  54441. });
  54442. MultiRenderTarget.prototype.resize = function (size) {
  54443. this.releaseInternalTextures();
  54444. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  54445. this._createInternalTextures();
  54446. };
  54447. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  54448. var _this = this;
  54449. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  54450. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  54451. });
  54452. };
  54453. MultiRenderTarget.prototype.dispose = function () {
  54454. this.releaseInternalTextures();
  54455. _super.prototype.dispose.call(this);
  54456. };
  54457. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  54458. if (!this._internalTextures) {
  54459. return;
  54460. }
  54461. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  54462. if (this._internalTextures[i] !== undefined) {
  54463. this._internalTextures[i].dispose();
  54464. this._internalTextures.splice(i, 1);
  54465. }
  54466. }
  54467. };
  54468. return MultiRenderTarget;
  54469. }(BABYLON.RenderTargetTexture));
  54470. BABYLON.MultiRenderTarget = MultiRenderTarget;
  54471. })(BABYLON || (BABYLON = {}));
  54472. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  54473. var BABYLON;
  54474. (function (BABYLON) {
  54475. var MirrorTexture = /** @class */ (function (_super) {
  54476. __extends(MirrorTexture, _super);
  54477. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  54478. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  54479. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  54480. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  54481. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  54482. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  54483. _this._transformMatrix = BABYLON.Matrix.Zero();
  54484. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  54485. _this._adaptiveBlurKernel = 0;
  54486. _this._blurKernelX = 0;
  54487. _this._blurKernelY = 0;
  54488. _this._blurRatio = 1.0;
  54489. _this.ignoreCameraViewport = true;
  54490. _this.onBeforeRenderObservable.add(function () {
  54491. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  54492. _this._savedViewMatrix = scene.getViewMatrix();
  54493. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  54494. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  54495. scene.clipPlane = _this.mirrorPlane;
  54496. scene.getEngine().cullBackFaces = false;
  54497. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  54498. });
  54499. _this.onAfterRenderObservable.add(function () {
  54500. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  54501. scene.getEngine().cullBackFaces = true;
  54502. scene._mirroredCameraPosition = null;
  54503. delete scene.clipPlane;
  54504. });
  54505. return _this;
  54506. }
  54507. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  54508. get: function () {
  54509. return this._blurRatio;
  54510. },
  54511. set: function (value) {
  54512. if (this._blurRatio === value) {
  54513. return;
  54514. }
  54515. this._blurRatio = value;
  54516. this._preparePostProcesses();
  54517. },
  54518. enumerable: true,
  54519. configurable: true
  54520. });
  54521. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  54522. set: function (value) {
  54523. this._adaptiveBlurKernel = value;
  54524. this._autoComputeBlurKernel();
  54525. },
  54526. enumerable: true,
  54527. configurable: true
  54528. });
  54529. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  54530. set: function (value) {
  54531. this.blurKernelX = value;
  54532. this.blurKernelY = value;
  54533. },
  54534. enumerable: true,
  54535. configurable: true
  54536. });
  54537. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  54538. get: function () {
  54539. return this._blurKernelX;
  54540. },
  54541. set: function (value) {
  54542. if (this._blurKernelX === value) {
  54543. return;
  54544. }
  54545. this._blurKernelX = value;
  54546. this._preparePostProcesses();
  54547. },
  54548. enumerable: true,
  54549. configurable: true
  54550. });
  54551. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  54552. get: function () {
  54553. return this._blurKernelY;
  54554. },
  54555. set: function (value) {
  54556. if (this._blurKernelY === value) {
  54557. return;
  54558. }
  54559. this._blurKernelY = value;
  54560. this._preparePostProcesses();
  54561. },
  54562. enumerable: true,
  54563. configurable: true
  54564. });
  54565. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  54566. var engine = this.getScene().getEngine();
  54567. var dw = this.getRenderWidth() / engine.getRenderWidth();
  54568. var dh = this.getRenderHeight() / engine.getRenderHeight();
  54569. this.blurKernelX = this._adaptiveBlurKernel * dw;
  54570. this.blurKernelY = this._adaptiveBlurKernel * dh;
  54571. };
  54572. MirrorTexture.prototype._onRatioRescale = function () {
  54573. if (this._sizeRatio) {
  54574. this.resize(this._initialSizeParameter);
  54575. if (!this._adaptiveBlurKernel) {
  54576. this._preparePostProcesses();
  54577. }
  54578. }
  54579. if (this._adaptiveBlurKernel) {
  54580. this._autoComputeBlurKernel();
  54581. }
  54582. };
  54583. MirrorTexture.prototype._preparePostProcesses = function () {
  54584. this.clearPostProcesses(true);
  54585. if (this._blurKernelX && this._blurKernelY) {
  54586. var engine = this.getScene().getEngine();
  54587. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  54588. 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);
  54589. this._blurX.autoClear = false;
  54590. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  54591. this._blurX.outputTexture = this._texture;
  54592. }
  54593. else {
  54594. this._blurX.alwaysForcePOT = true;
  54595. }
  54596. 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);
  54597. this._blurY.autoClear = false;
  54598. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  54599. this.addPostProcess(this._blurX);
  54600. this.addPostProcess(this._blurY);
  54601. }
  54602. else {
  54603. if (this._blurY) {
  54604. this.removePostProcess(this._blurY);
  54605. this._blurY.dispose();
  54606. this._blurY = null;
  54607. }
  54608. if (this._blurX) {
  54609. this.removePostProcess(this._blurX);
  54610. this._blurX.dispose();
  54611. this._blurX = null;
  54612. }
  54613. }
  54614. };
  54615. MirrorTexture.prototype.clone = function () {
  54616. var scene = this.getScene();
  54617. if (!scene) {
  54618. return this;
  54619. }
  54620. var textureSize = this.getSize();
  54621. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  54622. // Base texture
  54623. newTexture.hasAlpha = this.hasAlpha;
  54624. newTexture.level = this.level;
  54625. // Mirror Texture
  54626. newTexture.mirrorPlane = this.mirrorPlane.clone();
  54627. if (this.renderList) {
  54628. newTexture.renderList = this.renderList.slice(0);
  54629. }
  54630. return newTexture;
  54631. };
  54632. MirrorTexture.prototype.serialize = function () {
  54633. if (!this.name) {
  54634. return null;
  54635. }
  54636. var serializationObject = _super.prototype.serialize.call(this);
  54637. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  54638. return serializationObject;
  54639. };
  54640. return MirrorTexture;
  54641. }(BABYLON.RenderTargetTexture));
  54642. BABYLON.MirrorTexture = MirrorTexture;
  54643. })(BABYLON || (BABYLON = {}));
  54644. //# sourceMappingURL=babylon.mirrorTexture.js.map
  54645. var BABYLON;
  54646. (function (BABYLON) {
  54647. /**
  54648. * Creates a refraction texture used by refraction channel of the standard material.
  54649. * @param name the texture name
  54650. * @param size size of the underlying texture
  54651. * @param scene root scene
  54652. */
  54653. var RefractionTexture = /** @class */ (function (_super) {
  54654. __extends(RefractionTexture, _super);
  54655. function RefractionTexture(name, size, scene, generateMipMaps) {
  54656. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  54657. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  54658. _this.depth = 2.0;
  54659. _this.onBeforeRenderObservable.add(function () {
  54660. scene.clipPlane = _this.refractionPlane;
  54661. });
  54662. _this.onAfterRenderObservable.add(function () {
  54663. delete scene.clipPlane;
  54664. });
  54665. return _this;
  54666. }
  54667. RefractionTexture.prototype.clone = function () {
  54668. var scene = this.getScene();
  54669. if (!scene) {
  54670. return this;
  54671. }
  54672. var textureSize = this.getSize();
  54673. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  54674. // Base texture
  54675. newTexture.hasAlpha = this.hasAlpha;
  54676. newTexture.level = this.level;
  54677. // Refraction Texture
  54678. newTexture.refractionPlane = this.refractionPlane.clone();
  54679. if (this.renderList) {
  54680. newTexture.renderList = this.renderList.slice(0);
  54681. }
  54682. newTexture.depth = this.depth;
  54683. return newTexture;
  54684. };
  54685. RefractionTexture.prototype.serialize = function () {
  54686. if (!this.name) {
  54687. return null;
  54688. }
  54689. var serializationObject = _super.prototype.serialize.call(this);
  54690. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  54691. serializationObject.depth = this.depth;
  54692. return serializationObject;
  54693. };
  54694. return RefractionTexture;
  54695. }(BABYLON.RenderTargetTexture));
  54696. BABYLON.RefractionTexture = RefractionTexture;
  54697. })(BABYLON || (BABYLON = {}));
  54698. //# sourceMappingURL=babylon.refractionTexture.js.map
  54699. var BABYLON;
  54700. (function (BABYLON) {
  54701. var DynamicTexture = /** @class */ (function (_super) {
  54702. __extends(DynamicTexture, _super);
  54703. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  54704. if (scene === void 0) { scene = null; }
  54705. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54706. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  54707. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  54708. _this.name = name;
  54709. _this._engine = _this.getScene().getEngine();
  54710. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54711. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54712. _this._generateMipMaps = generateMipMaps;
  54713. if (options.getContext) {
  54714. _this._canvas = options;
  54715. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  54716. }
  54717. else {
  54718. _this._canvas = document.createElement("canvas");
  54719. if (options.width) {
  54720. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  54721. }
  54722. else {
  54723. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  54724. }
  54725. }
  54726. var textureSize = _this.getSize();
  54727. _this._canvas.width = textureSize.width;
  54728. _this._canvas.height = textureSize.height;
  54729. _this._context = _this._canvas.getContext("2d");
  54730. return _this;
  54731. }
  54732. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  54733. get: function () {
  54734. return true;
  54735. },
  54736. enumerable: true,
  54737. configurable: true
  54738. });
  54739. DynamicTexture.prototype._recreate = function (textureSize) {
  54740. this._canvas.width = textureSize.width;
  54741. this._canvas.height = textureSize.height;
  54742. this.releaseInternalTexture();
  54743. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  54744. };
  54745. DynamicTexture.prototype.scale = function (ratio) {
  54746. var textureSize = this.getSize();
  54747. textureSize.width *= ratio;
  54748. textureSize.height *= ratio;
  54749. this._recreate(textureSize);
  54750. };
  54751. DynamicTexture.prototype.scaleTo = function (width, height) {
  54752. var textureSize = this.getSize();
  54753. textureSize.width = width;
  54754. textureSize.height = height;
  54755. this._recreate(textureSize);
  54756. };
  54757. DynamicTexture.prototype.getContext = function () {
  54758. return this._context;
  54759. };
  54760. DynamicTexture.prototype.clear = function () {
  54761. var size = this.getSize();
  54762. this._context.fillRect(0, 0, size.width, size.height);
  54763. };
  54764. DynamicTexture.prototype.update = function (invertY) {
  54765. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  54766. };
  54767. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  54768. if (update === void 0) { update = true; }
  54769. var size = this.getSize();
  54770. if (clearColor) {
  54771. this._context.fillStyle = clearColor;
  54772. this._context.fillRect(0, 0, size.width, size.height);
  54773. }
  54774. this._context.font = font;
  54775. if (x === null || x === undefined) {
  54776. var textSize = this._context.measureText(text);
  54777. x = (size.width - textSize.width) / 2;
  54778. }
  54779. if (y === null || y === undefined) {
  54780. var fontSize = parseInt((font.replace(/\D/g, '')));
  54781. ;
  54782. y = (size.height / 2) + (fontSize / 3.65);
  54783. }
  54784. this._context.fillStyle = color;
  54785. this._context.fillText(text, x, y);
  54786. if (update) {
  54787. this.update(invertY);
  54788. }
  54789. };
  54790. DynamicTexture.prototype.clone = function () {
  54791. var scene = this.getScene();
  54792. if (!scene) {
  54793. return this;
  54794. }
  54795. var textureSize = this.getSize();
  54796. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  54797. // Base texture
  54798. newTexture.hasAlpha = this.hasAlpha;
  54799. newTexture.level = this.level;
  54800. // Dynamic Texture
  54801. newTexture.wrapU = this.wrapU;
  54802. newTexture.wrapV = this.wrapV;
  54803. return newTexture;
  54804. };
  54805. DynamicTexture.prototype._rebuild = function () {
  54806. this.update();
  54807. };
  54808. return DynamicTexture;
  54809. }(BABYLON.Texture));
  54810. BABYLON.DynamicTexture = DynamicTexture;
  54811. })(BABYLON || (BABYLON = {}));
  54812. //# sourceMappingURL=babylon.dynamicTexture.js.map
  54813. var BABYLON;
  54814. (function (BABYLON) {
  54815. var VideoTexture = /** @class */ (function (_super) {
  54816. __extends(VideoTexture, _super);
  54817. /**
  54818. * Creates a video texture.
  54819. * Sample : https://doc.babylonjs.com/how_to/video_texture
  54820. * @param {string | null} name optional name, will detect from video source, if not defined
  54821. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  54822. * @param {BABYLON.Scene} scene is obviously the current scene.
  54823. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  54824. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  54825. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  54826. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  54827. */
  54828. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  54829. if (generateMipMaps === void 0) { generateMipMaps = false; }
  54830. if (invertY === void 0) { invertY = false; }
  54831. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54832. if (settings === void 0) { settings = {
  54833. autoPlay: true,
  54834. loop: true,
  54835. autoUpdateTexture: true,
  54836. }; }
  54837. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  54838. _this._createInternalTexture = function () {
  54839. if (_this._texture != null) {
  54840. return;
  54841. }
  54842. if (!_this._engine.needPOTTextures ||
  54843. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  54844. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  54845. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  54846. }
  54847. else {
  54848. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54849. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54850. _this._generateMipMaps = false;
  54851. }
  54852. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  54853. _this._texture.isReady = true;
  54854. _this._updateInternalTexture();
  54855. };
  54856. _this.reset = function () {
  54857. if (_this._texture == null) {
  54858. return;
  54859. }
  54860. _this._texture.dispose();
  54861. _this._texture = null;
  54862. };
  54863. _this._updateInternalTexture = function (e) {
  54864. if (_this._texture == null || !_this._texture.isReady) {
  54865. return;
  54866. }
  54867. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  54868. return;
  54869. }
  54870. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  54871. };
  54872. _this._engine = _this.getScene().getEngine();
  54873. _this._generateMipMaps = generateMipMaps;
  54874. _this._samplingMode = samplingMode;
  54875. _this.autoUpdateTexture = settings.autoUpdateTexture;
  54876. _this.name = name || _this._getName(src);
  54877. _this.video = _this._getVideo(src);
  54878. if (settings.autoPlay !== undefined) {
  54879. _this.video.autoplay = settings.autoPlay;
  54880. }
  54881. if (settings.loop !== undefined) {
  54882. _this.video.loop = settings.loop;
  54883. }
  54884. _this.video.addEventListener("canplay", _this._createInternalTexture);
  54885. _this.video.addEventListener("paused", _this._updateInternalTexture);
  54886. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  54887. _this.video.addEventListener("emptied", _this.reset);
  54888. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  54889. _this._createInternalTexture();
  54890. }
  54891. return _this;
  54892. }
  54893. VideoTexture.prototype._getName = function (src) {
  54894. if (src instanceof HTMLVideoElement) {
  54895. return src.currentSrc;
  54896. }
  54897. if (typeof src === "object") {
  54898. return src.toString();
  54899. }
  54900. return src;
  54901. };
  54902. ;
  54903. VideoTexture.prototype._getVideo = function (src) {
  54904. if (src instanceof HTMLVideoElement) {
  54905. return src;
  54906. }
  54907. var video = document.createElement("video");
  54908. if (typeof src === "string") {
  54909. video.src = src;
  54910. }
  54911. else {
  54912. src.forEach(function (url) {
  54913. var source = document.createElement("source");
  54914. source.src = url;
  54915. video.appendChild(source);
  54916. });
  54917. }
  54918. return video;
  54919. };
  54920. ;
  54921. /**
  54922. * Internal method to initiate `update`.
  54923. */
  54924. VideoTexture.prototype._rebuild = function () {
  54925. this.update();
  54926. };
  54927. /**
  54928. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  54929. */
  54930. VideoTexture.prototype.update = function () {
  54931. if (!this.autoUpdateTexture) {
  54932. // Expecting user to call `updateTexture` manually
  54933. return;
  54934. }
  54935. this.updateTexture(true);
  54936. };
  54937. /**
  54938. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  54939. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  54940. */
  54941. VideoTexture.prototype.updateTexture = function (isVisible) {
  54942. if (!isVisible) {
  54943. return;
  54944. }
  54945. if (this.video.paused) {
  54946. return;
  54947. }
  54948. this._updateInternalTexture();
  54949. };
  54950. /**
  54951. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  54952. * @param url New url.
  54953. */
  54954. VideoTexture.prototype.updateURL = function (url) {
  54955. this.video.src = url;
  54956. };
  54957. VideoTexture.prototype.dispose = function () {
  54958. _super.prototype.dispose.call(this);
  54959. this.video.removeEventListener("canplay", this._createInternalTexture);
  54960. this.video.removeEventListener("paused", this._updateInternalTexture);
  54961. this.video.removeEventListener("seeked", this._updateInternalTexture);
  54962. this.video.removeEventListener("emptied", this.reset);
  54963. };
  54964. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  54965. var video = document.createElement("video");
  54966. var constraintsDeviceId;
  54967. if (constraints && constraints.deviceId) {
  54968. constraintsDeviceId = {
  54969. exact: constraints.deviceId,
  54970. };
  54971. }
  54972. navigator.getUserMedia =
  54973. navigator.getUserMedia ||
  54974. navigator.webkitGetUserMedia ||
  54975. navigator.mozGetUserMedia ||
  54976. navigator.msGetUserMedia;
  54977. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  54978. if (navigator.getUserMedia) {
  54979. navigator.getUserMedia({
  54980. video: {
  54981. deviceId: constraintsDeviceId,
  54982. width: {
  54983. min: (constraints && constraints.minWidth) || 256,
  54984. max: (constraints && constraints.maxWidth) || 640,
  54985. },
  54986. height: {
  54987. min: (constraints && constraints.minHeight) || 256,
  54988. max: (constraints && constraints.maxHeight) || 480,
  54989. },
  54990. },
  54991. }, function (stream) {
  54992. if (video.mozSrcObject !== undefined) {
  54993. // hack for Firefox < 19
  54994. video.mozSrcObject = stream;
  54995. }
  54996. else {
  54997. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  54998. }
  54999. video.play();
  55000. if (onReady) {
  55001. onReady(new VideoTexture("video", video, scene, true, true));
  55002. }
  55003. }, function (e) {
  55004. BABYLON.Tools.Error(e.name);
  55005. });
  55006. }
  55007. };
  55008. return VideoTexture;
  55009. }(BABYLON.Texture));
  55010. BABYLON.VideoTexture = VideoTexture;
  55011. })(BABYLON || (BABYLON = {}));
  55012. //# sourceMappingURL=babylon.videoTexture.js.map
  55013. var BABYLON;
  55014. (function (BABYLON) {
  55015. var RawTexture = /** @class */ (function (_super) {
  55016. __extends(RawTexture, _super);
  55017. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  55018. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55019. if (invertY === void 0) { invertY = false; }
  55020. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55021. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55022. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  55023. _this.format = format;
  55024. _this._engine = scene.getEngine();
  55025. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  55026. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55027. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55028. return _this;
  55029. }
  55030. RawTexture.prototype.update = function (data) {
  55031. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  55032. };
  55033. // Statics
  55034. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  55035. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55036. if (invertY === void 0) { invertY = false; }
  55037. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55038. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  55039. };
  55040. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  55041. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55042. if (invertY === void 0) { invertY = false; }
  55043. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55044. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  55045. };
  55046. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  55047. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55048. if (invertY === void 0) { invertY = false; }
  55049. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55050. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  55051. };
  55052. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  55053. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55054. if (invertY === void 0) { invertY = false; }
  55055. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55056. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55057. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  55058. };
  55059. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  55060. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55061. if (invertY === void 0) { invertY = false; }
  55062. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55063. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55064. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  55065. };
  55066. return RawTexture;
  55067. }(BABYLON.Texture));
  55068. BABYLON.RawTexture = RawTexture;
  55069. })(BABYLON || (BABYLON = {}));
  55070. //# sourceMappingURL=babylon.rawTexture.js.map
  55071. var BABYLON;
  55072. (function (BABYLON) {
  55073. var PostProcess = /** @class */ (function () {
  55074. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  55075. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  55076. if (defines === void 0) { defines = null; }
  55077. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55078. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  55079. if (blockCompilation === void 0) { blockCompilation = false; }
  55080. this.name = name;
  55081. this.width = -1;
  55082. this.height = -1;
  55083. this.autoClear = true;
  55084. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  55085. this.animations = new Array();
  55086. /*
  55087. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  55088. Can only be used on a single postprocess or on the last one of a chain.
  55089. */
  55090. this.enablePixelPerfectMode = false;
  55091. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  55092. this.alwaysForcePOT = false;
  55093. this.samples = 1;
  55094. this.adaptScaleToCurrentViewport = false;
  55095. this._reusable = false;
  55096. this._textures = new BABYLON.SmartArray(2);
  55097. this._currentRenderTextureInd = 0;
  55098. this._scaleRatio = new BABYLON.Vector2(1, 1);
  55099. this._texelSize = BABYLON.Vector2.Zero();
  55100. // Events
  55101. /**
  55102. * An event triggered when the postprocess is activated.
  55103. * @type {BABYLON.Observable}
  55104. */
  55105. this.onActivateObservable = new BABYLON.Observable();
  55106. /**
  55107. * An event triggered when the postprocess changes its size.
  55108. * @type {BABYLON.Observable}
  55109. */
  55110. this.onSizeChangedObservable = new BABYLON.Observable();
  55111. /**
  55112. * An event triggered when the postprocess applies its effect.
  55113. * @type {BABYLON.Observable}
  55114. */
  55115. this.onApplyObservable = new BABYLON.Observable();
  55116. /**
  55117. * An event triggered before rendering the postprocess
  55118. * @type {BABYLON.Observable}
  55119. */
  55120. this.onBeforeRenderObservable = new BABYLON.Observable();
  55121. /**
  55122. * An event triggered after rendering the postprocess
  55123. * @type {BABYLON.Observable}
  55124. */
  55125. this.onAfterRenderObservable = new BABYLON.Observable();
  55126. if (camera != null) {
  55127. this._camera = camera;
  55128. this._scene = camera.getScene();
  55129. camera.attachPostProcess(this);
  55130. this._engine = this._scene.getEngine();
  55131. this._scene.postProcesses.push(this);
  55132. }
  55133. else if (engine) {
  55134. this._engine = engine;
  55135. this._engine.postProcesses.push(this);
  55136. }
  55137. this._options = options;
  55138. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  55139. this._reusable = reusable || false;
  55140. this._textureType = textureType;
  55141. this._samplers = samplers || [];
  55142. this._samplers.push("textureSampler");
  55143. this._fragmentUrl = fragmentUrl;
  55144. this._vertexUrl = vertexUrl;
  55145. this._parameters = parameters || [];
  55146. this._parameters.push("scale");
  55147. this._indexParameters = indexParameters;
  55148. if (!blockCompilation) {
  55149. this.updateEffect(defines);
  55150. }
  55151. }
  55152. Object.defineProperty(PostProcess.prototype, "onActivate", {
  55153. set: function (callback) {
  55154. if (this._onActivateObserver) {
  55155. this.onActivateObservable.remove(this._onActivateObserver);
  55156. }
  55157. if (callback) {
  55158. this._onActivateObserver = this.onActivateObservable.add(callback);
  55159. }
  55160. },
  55161. enumerable: true,
  55162. configurable: true
  55163. });
  55164. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  55165. set: function (callback) {
  55166. if (this._onSizeChangedObserver) {
  55167. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  55168. }
  55169. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  55170. },
  55171. enumerable: true,
  55172. configurable: true
  55173. });
  55174. Object.defineProperty(PostProcess.prototype, "onApply", {
  55175. set: function (callback) {
  55176. if (this._onApplyObserver) {
  55177. this.onApplyObservable.remove(this._onApplyObserver);
  55178. }
  55179. this._onApplyObserver = this.onApplyObservable.add(callback);
  55180. },
  55181. enumerable: true,
  55182. configurable: true
  55183. });
  55184. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  55185. set: function (callback) {
  55186. if (this._onBeforeRenderObserver) {
  55187. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  55188. }
  55189. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  55190. },
  55191. enumerable: true,
  55192. configurable: true
  55193. });
  55194. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  55195. set: function (callback) {
  55196. if (this._onAfterRenderObserver) {
  55197. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  55198. }
  55199. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  55200. },
  55201. enumerable: true,
  55202. configurable: true
  55203. });
  55204. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  55205. get: function () {
  55206. return this._textures.data[this._currentRenderTextureInd];
  55207. },
  55208. set: function (value) {
  55209. this._forcedOutputTexture = value;
  55210. },
  55211. enumerable: true,
  55212. configurable: true
  55213. });
  55214. PostProcess.prototype.getCamera = function () {
  55215. return this._camera;
  55216. };
  55217. Object.defineProperty(PostProcess.prototype, "texelSize", {
  55218. get: function () {
  55219. if (this._shareOutputWithPostProcess) {
  55220. return this._shareOutputWithPostProcess.texelSize;
  55221. }
  55222. if (this._forcedOutputTexture) {
  55223. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  55224. }
  55225. return this._texelSize;
  55226. },
  55227. enumerable: true,
  55228. configurable: true
  55229. });
  55230. PostProcess.prototype.getEngine = function () {
  55231. return this._engine;
  55232. };
  55233. PostProcess.prototype.getEffect = function () {
  55234. return this._effect;
  55235. };
  55236. PostProcess.prototype.shareOutputWith = function (postProcess) {
  55237. this._disposeTextures();
  55238. this._shareOutputWithPostProcess = postProcess;
  55239. return this;
  55240. };
  55241. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  55242. if (defines === void 0) { defines = null; }
  55243. if (uniforms === void 0) { uniforms = null; }
  55244. if (samplers === void 0) { samplers = null; }
  55245. 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);
  55246. };
  55247. PostProcess.prototype.isReusable = function () {
  55248. return this._reusable;
  55249. };
  55250. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  55251. PostProcess.prototype.markTextureDirty = function () {
  55252. this.width = -1;
  55253. };
  55254. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  55255. var _this = this;
  55256. if (sourceTexture === void 0) { sourceTexture = null; }
  55257. camera = camera || this._camera;
  55258. var scene = camera.getScene();
  55259. var engine = scene.getEngine();
  55260. var maxSize = engine.getCaps().maxTextureSize;
  55261. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  55262. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  55263. var desiredWidth = (this._options.width || requiredWidth);
  55264. var desiredHeight = this._options.height || requiredHeight;
  55265. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  55266. if (this.adaptScaleToCurrentViewport) {
  55267. var currentViewport = engine.currentViewport;
  55268. if (currentViewport) {
  55269. desiredWidth *= currentViewport.width;
  55270. desiredHeight *= currentViewport.height;
  55271. }
  55272. }
  55273. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  55274. if (!this._options.width) {
  55275. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  55276. }
  55277. if (!this._options.height) {
  55278. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  55279. }
  55280. }
  55281. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  55282. if (this._textures.length > 0) {
  55283. for (var i = 0; i < this._textures.length; i++) {
  55284. this._engine._releaseTexture(this._textures.data[i]);
  55285. }
  55286. this._textures.reset();
  55287. }
  55288. this.width = desiredWidth;
  55289. this.height = desiredHeight;
  55290. var textureSize = { width: this.width, height: this.height };
  55291. var textureOptions = {
  55292. generateMipMaps: false,
  55293. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  55294. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  55295. samplingMode: this.renderTargetSamplingMode,
  55296. type: this._textureType
  55297. };
  55298. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  55299. if (this._reusable) {
  55300. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  55301. }
  55302. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  55303. this.onSizeChangedObservable.notifyObservers(this);
  55304. }
  55305. this._textures.forEach(function (texture) {
  55306. if (texture.samples !== _this.samples) {
  55307. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  55308. }
  55309. });
  55310. }
  55311. var target;
  55312. if (this._shareOutputWithPostProcess) {
  55313. target = this._shareOutputWithPostProcess.outputTexture;
  55314. }
  55315. else if (this._forcedOutputTexture) {
  55316. target = this._forcedOutputTexture;
  55317. this.width = this._forcedOutputTexture.width;
  55318. this.height = this._forcedOutputTexture.height;
  55319. }
  55320. else {
  55321. target = this.outputTexture;
  55322. }
  55323. if (this.enablePixelPerfectMode) {
  55324. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  55325. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  55326. }
  55327. else {
  55328. this._scaleRatio.copyFromFloats(1, 1);
  55329. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  55330. }
  55331. this.onActivateObservable.notifyObservers(camera);
  55332. // Clear
  55333. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  55334. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  55335. }
  55336. if (this._reusable) {
  55337. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  55338. }
  55339. };
  55340. Object.defineProperty(PostProcess.prototype, "isSupported", {
  55341. get: function () {
  55342. return this._effect.isSupported;
  55343. },
  55344. enumerable: true,
  55345. configurable: true
  55346. });
  55347. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  55348. get: function () {
  55349. if (this._shareOutputWithPostProcess) {
  55350. return this._shareOutputWithPostProcess.aspectRatio;
  55351. }
  55352. if (this._forcedOutputTexture) {
  55353. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  55354. }
  55355. return this.width / this.height;
  55356. },
  55357. enumerable: true,
  55358. configurable: true
  55359. });
  55360. /**
  55361. * Get a value indicating if the post-process is ready to be used
  55362. * @returns true if the post-process is ready (shader is compiled)
  55363. */
  55364. PostProcess.prototype.isReady = function () {
  55365. return this._effect && this._effect.isReady();
  55366. };
  55367. PostProcess.prototype.apply = function () {
  55368. // Check
  55369. if (!this._effect || !this._effect.isReady())
  55370. return null;
  55371. // States
  55372. this._engine.enableEffect(this._effect);
  55373. this._engine.setState(false);
  55374. this._engine.setDepthBuffer(false);
  55375. this._engine.setDepthWrite(false);
  55376. // Alpha
  55377. this._engine.setAlphaMode(this.alphaMode);
  55378. if (this.alphaConstants) {
  55379. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  55380. }
  55381. // Texture
  55382. var source;
  55383. if (this._shareOutputWithPostProcess) {
  55384. source = this._shareOutputWithPostProcess.outputTexture;
  55385. }
  55386. else if (this._forcedOutputTexture) {
  55387. source = this._forcedOutputTexture;
  55388. }
  55389. else {
  55390. source = this.outputTexture;
  55391. }
  55392. this._effect._bindTexture("textureSampler", source);
  55393. // Parameters
  55394. this._effect.setVector2("scale", this._scaleRatio);
  55395. this.onApplyObservable.notifyObservers(this._effect);
  55396. return this._effect;
  55397. };
  55398. PostProcess.prototype._disposeTextures = function () {
  55399. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  55400. return;
  55401. }
  55402. if (this._textures.length > 0) {
  55403. for (var i = 0; i < this._textures.length; i++) {
  55404. this._engine._releaseTexture(this._textures.data[i]);
  55405. }
  55406. }
  55407. this._textures.dispose();
  55408. };
  55409. PostProcess.prototype.dispose = function (camera) {
  55410. camera = camera || this._camera;
  55411. this._disposeTextures();
  55412. if (this._scene) {
  55413. var index_1 = this._scene.postProcesses.indexOf(this);
  55414. if (index_1 !== -1) {
  55415. this._scene.postProcesses.splice(index_1, 1);
  55416. }
  55417. }
  55418. else {
  55419. var index_2 = this._engine.postProcesses.indexOf(this);
  55420. if (index_2 !== -1) {
  55421. this._engine.postProcesses.splice(index_2, 1);
  55422. }
  55423. }
  55424. if (!camera) {
  55425. return;
  55426. }
  55427. camera.detachPostProcess(this);
  55428. var index = camera._postProcesses.indexOf(this);
  55429. if (index === 0 && camera._postProcesses.length > 0) {
  55430. this._camera._postProcesses[0].markTextureDirty();
  55431. }
  55432. this.onActivateObservable.clear();
  55433. this.onAfterRenderObservable.clear();
  55434. this.onApplyObservable.clear();
  55435. this.onBeforeRenderObservable.clear();
  55436. this.onSizeChangedObservable.clear();
  55437. };
  55438. return PostProcess;
  55439. }());
  55440. BABYLON.PostProcess = PostProcess;
  55441. })(BABYLON || (BABYLON = {}));
  55442. //# sourceMappingURL=babylon.postProcess.js.map
  55443. var BABYLON;
  55444. (function (BABYLON) {
  55445. var PassPostProcess = /** @class */ (function (_super) {
  55446. __extends(PassPostProcess, _super);
  55447. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  55448. if (camera === void 0) { camera = null; }
  55449. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55450. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  55451. }
  55452. return PassPostProcess;
  55453. }(BABYLON.PostProcess));
  55454. BABYLON.PassPostProcess = PassPostProcess;
  55455. })(BABYLON || (BABYLON = {}));
  55456. //# sourceMappingURL=babylon.passPostProcess.js.map
  55457. var __assign = (this && this.__assign) || Object.assign || function(t) {
  55458. for (var s, i = 1, n = arguments.length; i < n; i++) {
  55459. s = arguments[i];
  55460. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  55461. t[p] = s[p];
  55462. }
  55463. return t;
  55464. };
  55465. var BABYLON;
  55466. (function (BABYLON) {
  55467. var ShadowGenerator = /** @class */ (function () {
  55468. /**
  55469. * Creates a ShadowGenerator object.
  55470. * A ShadowGenerator is the required tool to use the shadows.
  55471. * Each light casting shadows needs to use its own ShadowGenerator.
  55472. * Required parameters :
  55473. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  55474. * - `light`: the light object generating the shadows.
  55475. * - `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.
  55476. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  55477. */
  55478. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  55479. // Members
  55480. this._bias = 0.00005;
  55481. this._blurBoxOffset = 1;
  55482. this._blurScale = 2;
  55483. this._blurKernel = 1;
  55484. this._useKernelBlur = false;
  55485. this._filter = ShadowGenerator.FILTER_NONE;
  55486. this._darkness = 0;
  55487. this._transparencyShadow = false;
  55488. /**
  55489. * Controls the extent to which the shadows fade out at the edge of the frustum
  55490. * Used only by directionals and spots
  55491. */
  55492. this.frustumEdgeFalloff = 0;
  55493. this.forceBackFacesOnly = false;
  55494. this._lightDirection = BABYLON.Vector3.Zero();
  55495. this._viewMatrix = BABYLON.Matrix.Zero();
  55496. this._projectionMatrix = BABYLON.Matrix.Zero();
  55497. this._transformMatrix = BABYLON.Matrix.Zero();
  55498. this._currentFaceIndex = 0;
  55499. this._currentFaceIndexCache = 0;
  55500. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  55501. this._mapSize = mapSize;
  55502. this._light = light;
  55503. this._scene = light.getScene();
  55504. light._shadowGenerator = this;
  55505. // Texture type fallback from float to int if not supported.
  55506. var caps = this._scene.getEngine().getCaps();
  55507. if (!useFullFloatFirst) {
  55508. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  55509. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  55510. }
  55511. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  55512. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  55513. }
  55514. else {
  55515. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  55516. }
  55517. }
  55518. else {
  55519. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  55520. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  55521. }
  55522. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  55523. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  55524. }
  55525. else {
  55526. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  55527. }
  55528. }
  55529. this._initializeGenerator();
  55530. }
  55531. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  55532. // Static
  55533. get: function () {
  55534. return ShadowGenerator._FILTER_NONE;
  55535. },
  55536. enumerable: true,
  55537. configurable: true
  55538. });
  55539. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  55540. get: function () {
  55541. return ShadowGenerator._FILTER_POISSONSAMPLING;
  55542. },
  55543. enumerable: true,
  55544. configurable: true
  55545. });
  55546. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  55547. get: function () {
  55548. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  55549. },
  55550. enumerable: true,
  55551. configurable: true
  55552. });
  55553. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  55554. get: function () {
  55555. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  55556. },
  55557. enumerable: true,
  55558. configurable: true
  55559. });
  55560. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  55561. get: function () {
  55562. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  55563. },
  55564. enumerable: true,
  55565. configurable: true
  55566. });
  55567. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  55568. get: function () {
  55569. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  55570. },
  55571. enumerable: true,
  55572. configurable: true
  55573. });
  55574. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  55575. get: function () {
  55576. return this._bias;
  55577. },
  55578. set: function (bias) {
  55579. this._bias = bias;
  55580. },
  55581. enumerable: true,
  55582. configurable: true
  55583. });
  55584. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  55585. get: function () {
  55586. return this._blurBoxOffset;
  55587. },
  55588. set: function (value) {
  55589. if (this._blurBoxOffset === value) {
  55590. return;
  55591. }
  55592. this._blurBoxOffset = value;
  55593. this._disposeBlurPostProcesses();
  55594. },
  55595. enumerable: true,
  55596. configurable: true
  55597. });
  55598. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  55599. get: function () {
  55600. return this._blurScale;
  55601. },
  55602. set: function (value) {
  55603. if (this._blurScale === value) {
  55604. return;
  55605. }
  55606. this._blurScale = value;
  55607. this._disposeBlurPostProcesses();
  55608. },
  55609. enumerable: true,
  55610. configurable: true
  55611. });
  55612. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  55613. get: function () {
  55614. return this._blurKernel;
  55615. },
  55616. set: function (value) {
  55617. if (this._blurKernel === value) {
  55618. return;
  55619. }
  55620. this._blurKernel = value;
  55621. this._disposeBlurPostProcesses();
  55622. },
  55623. enumerable: true,
  55624. configurable: true
  55625. });
  55626. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  55627. get: function () {
  55628. return this._useKernelBlur;
  55629. },
  55630. set: function (value) {
  55631. if (this._useKernelBlur === value) {
  55632. return;
  55633. }
  55634. this._useKernelBlur = value;
  55635. this._disposeBlurPostProcesses();
  55636. },
  55637. enumerable: true,
  55638. configurable: true
  55639. });
  55640. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  55641. get: function () {
  55642. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  55643. },
  55644. set: function (value) {
  55645. this._depthScale = value;
  55646. },
  55647. enumerable: true,
  55648. configurable: true
  55649. });
  55650. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  55651. get: function () {
  55652. return this._filter;
  55653. },
  55654. set: function (value) {
  55655. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  55656. if (this._light.needCube()) {
  55657. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  55658. this.useExponentialShadowMap = true;
  55659. return;
  55660. }
  55661. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  55662. this.useCloseExponentialShadowMap = true;
  55663. return;
  55664. }
  55665. }
  55666. if (this._filter === value) {
  55667. return;
  55668. }
  55669. this._filter = value;
  55670. this._disposeBlurPostProcesses();
  55671. this._applyFilterValues();
  55672. this._light._markMeshesAsLightDirty();
  55673. },
  55674. enumerable: true,
  55675. configurable: true
  55676. });
  55677. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  55678. get: function () {
  55679. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  55680. },
  55681. set: function (value) {
  55682. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  55683. return;
  55684. }
  55685. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  55686. },
  55687. enumerable: true,
  55688. configurable: true
  55689. });
  55690. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  55691. get: function () {
  55692. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  55693. return this.useExponentialShadowMap;
  55694. },
  55695. set: function (value) {
  55696. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  55697. this.useExponentialShadowMap = value;
  55698. },
  55699. enumerable: true,
  55700. configurable: true
  55701. });
  55702. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  55703. get: function () {
  55704. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  55705. return this.useBlurExponentialShadowMap;
  55706. },
  55707. set: function (value) {
  55708. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  55709. this.useBlurExponentialShadowMap = value;
  55710. },
  55711. enumerable: true,
  55712. configurable: true
  55713. });
  55714. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  55715. get: function () {
  55716. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  55717. },
  55718. set: function (value) {
  55719. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  55720. return;
  55721. }
  55722. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  55723. },
  55724. enumerable: true,
  55725. configurable: true
  55726. });
  55727. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  55728. get: function () {
  55729. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  55730. },
  55731. set: function (value) {
  55732. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  55733. return;
  55734. }
  55735. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  55736. },
  55737. enumerable: true,
  55738. configurable: true
  55739. });
  55740. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  55741. get: function () {
  55742. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  55743. },
  55744. set: function (value) {
  55745. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  55746. return;
  55747. }
  55748. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  55749. },
  55750. enumerable: true,
  55751. configurable: true
  55752. });
  55753. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  55754. get: function () {
  55755. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  55756. },
  55757. set: function (value) {
  55758. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  55759. return;
  55760. }
  55761. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  55762. },
  55763. enumerable: true,
  55764. configurable: true
  55765. });
  55766. /**
  55767. * Returns the darkness value (float).
  55768. */
  55769. ShadowGenerator.prototype.getDarkness = function () {
  55770. return this._darkness;
  55771. };
  55772. /**
  55773. * Sets the ShadowGenerator darkness value (float <= 1.0).
  55774. * Returns the ShadowGenerator.
  55775. */
  55776. ShadowGenerator.prototype.setDarkness = function (darkness) {
  55777. if (darkness >= 1.0)
  55778. this._darkness = 1.0;
  55779. else if (darkness <= 0.0)
  55780. this._darkness = 0.0;
  55781. else
  55782. this._darkness = darkness;
  55783. return this;
  55784. };
  55785. /**
  55786. * Sets the ability to have transparent shadow (boolean).
  55787. * Returns the ShadowGenerator.
  55788. */
  55789. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  55790. this._transparencyShadow = hasShadow;
  55791. return this;
  55792. };
  55793. /**
  55794. * Returns a RenderTargetTexture object : the shadow map texture.
  55795. */
  55796. ShadowGenerator.prototype.getShadowMap = function () {
  55797. return this._shadowMap;
  55798. };
  55799. /**
  55800. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  55801. */
  55802. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  55803. if (this._shadowMap2) {
  55804. return this._shadowMap2;
  55805. }
  55806. return this._shadowMap;
  55807. };
  55808. /**
  55809. * Helper function to add a mesh and its descendants to the list of shadow casters
  55810. * @param mesh Mesh to add
  55811. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  55812. */
  55813. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  55814. if (includeDescendants === void 0) { includeDescendants = true; }
  55815. if (!this._shadowMap) {
  55816. return this;
  55817. }
  55818. if (!this._shadowMap.renderList) {
  55819. this._shadowMap.renderList = [];
  55820. }
  55821. this._shadowMap.renderList.push(mesh);
  55822. if (includeDescendants) {
  55823. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  55824. }
  55825. return this;
  55826. var _a;
  55827. };
  55828. /**
  55829. * Helper function to remove a mesh and its descendants from the list of shadow casters
  55830. * @param mesh Mesh to remove
  55831. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  55832. */
  55833. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  55834. if (includeDescendants === void 0) { includeDescendants = true; }
  55835. if (!this._shadowMap || !this._shadowMap.renderList) {
  55836. return this;
  55837. }
  55838. var index = this._shadowMap.renderList.indexOf(mesh);
  55839. if (index !== -1) {
  55840. this._shadowMap.renderList.splice(index, 1);
  55841. }
  55842. if (includeDescendants) {
  55843. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  55844. var child = _a[_i];
  55845. this.removeShadowCaster(child);
  55846. }
  55847. }
  55848. return this;
  55849. };
  55850. /**
  55851. * Returns the associated light object.
  55852. */
  55853. ShadowGenerator.prototype.getLight = function () {
  55854. return this._light;
  55855. };
  55856. ShadowGenerator.prototype._initializeGenerator = function () {
  55857. this._light._markMeshesAsLightDirty();
  55858. this._initializeShadowMap();
  55859. };
  55860. ShadowGenerator.prototype._initializeShadowMap = function () {
  55861. var _this = this;
  55862. // Render target
  55863. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  55864. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55865. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55866. this._shadowMap.anisotropicFilteringLevel = 1;
  55867. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  55868. this._shadowMap.renderParticles = false;
  55869. this._shadowMap.ignoreCameraViewport = true;
  55870. // Record Face Index before render.
  55871. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  55872. _this._currentFaceIndex = faceIndex;
  55873. });
  55874. // Custom render function.
  55875. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  55876. // Blur if required afer render.
  55877. this._shadowMap.onAfterUnbindObservable.add(function () {
  55878. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  55879. return;
  55880. }
  55881. var shadowMap = _this.getShadowMapForRendering();
  55882. if (shadowMap) {
  55883. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  55884. }
  55885. });
  55886. // Clear according to the chosen filter.
  55887. this._shadowMap.onClearObservable.add(function (engine) {
  55888. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  55889. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  55890. }
  55891. else {
  55892. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  55893. }
  55894. });
  55895. };
  55896. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  55897. var _this = this;
  55898. var engine = this._scene.getEngine();
  55899. var targetSize = this._mapSize / this.blurScale;
  55900. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  55901. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  55902. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55903. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55904. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  55905. }
  55906. if (this.useKernelBlur) {
  55907. 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);
  55908. this._kernelBlurXPostprocess.width = targetSize;
  55909. this._kernelBlurXPostprocess.height = targetSize;
  55910. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  55911. effect.setTexture("textureSampler", _this._shadowMap);
  55912. });
  55913. 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);
  55914. this._kernelBlurXPostprocess.autoClear = false;
  55915. this._kernelBlurYPostprocess.autoClear = false;
  55916. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  55917. this._kernelBlurXPostprocess.packedFloat = true;
  55918. this._kernelBlurYPostprocess.packedFloat = true;
  55919. }
  55920. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  55921. }
  55922. else {
  55923. 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);
  55924. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  55925. effect.setFloat2("screenSize", targetSize, targetSize);
  55926. effect.setTexture("textureSampler", _this._shadowMap);
  55927. });
  55928. this._boxBlurPostprocess.autoClear = false;
  55929. this._blurPostProcesses = [this._boxBlurPostprocess];
  55930. }
  55931. };
  55932. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  55933. var index;
  55934. var engine = this._scene.getEngine();
  55935. if (depthOnlySubMeshes.length) {
  55936. engine.setColorWrite(false);
  55937. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  55938. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  55939. }
  55940. engine.setColorWrite(true);
  55941. }
  55942. for (index = 0; index < opaqueSubMeshes.length; index++) {
  55943. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  55944. }
  55945. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  55946. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  55947. }
  55948. if (this._transparencyShadow) {
  55949. for (index = 0; index < transparentSubMeshes.length; index++) {
  55950. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  55951. }
  55952. }
  55953. };
  55954. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  55955. var _this = this;
  55956. var mesh = subMesh.getRenderingMesh();
  55957. var scene = this._scene;
  55958. var engine = scene.getEngine();
  55959. var material = subMesh.getMaterial();
  55960. if (!material) {
  55961. return;
  55962. }
  55963. // Culling
  55964. engine.setState(material.backFaceCulling);
  55965. // Managing instances
  55966. var batch = mesh._getInstancesRenderList(subMesh._id);
  55967. if (batch.mustReturn) {
  55968. return;
  55969. }
  55970. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  55971. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  55972. engine.enableEffect(this._effect);
  55973. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  55974. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  55975. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  55976. this._effect.setVector3("lightPosition", this.getLight().position);
  55977. if (scene.activeCamera) {
  55978. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  55979. }
  55980. // Alpha test
  55981. if (material && material.needAlphaTesting()) {
  55982. var alphaTexture = material.getAlphaTestTexture();
  55983. if (alphaTexture) {
  55984. this._effect.setTexture("diffuseSampler", alphaTexture);
  55985. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  55986. }
  55987. }
  55988. // Bones
  55989. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  55990. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  55991. }
  55992. if (this.forceBackFacesOnly) {
  55993. engine.setState(true, 0, false, true);
  55994. }
  55995. // Draw
  55996. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  55997. if (this.forceBackFacesOnly) {
  55998. engine.setState(true, 0, false, false);
  55999. }
  56000. }
  56001. else {
  56002. // Need to reset refresh rate of the shadowMap
  56003. if (this._shadowMap) {
  56004. this._shadowMap.resetRefreshCounter();
  56005. }
  56006. }
  56007. };
  56008. ShadowGenerator.prototype._applyFilterValues = function () {
  56009. if (!this._shadowMap) {
  56010. return;
  56011. }
  56012. if (this.filter === ShadowGenerator.FILTER_NONE) {
  56013. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  56014. }
  56015. else {
  56016. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  56017. }
  56018. };
  56019. /**
  56020. * Force shader compilation including textures ready check
  56021. */
  56022. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  56023. var _this = this;
  56024. var localOptions = __assign({ useInstances: false }, options);
  56025. var shadowMap = this.getShadowMap();
  56026. if (!shadowMap) {
  56027. if (onCompiled) {
  56028. onCompiled(this);
  56029. }
  56030. return;
  56031. }
  56032. var renderList = shadowMap.renderList;
  56033. if (!renderList) {
  56034. if (onCompiled) {
  56035. onCompiled(this);
  56036. }
  56037. return;
  56038. }
  56039. var subMeshes = new Array();
  56040. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  56041. var mesh = renderList_1[_i];
  56042. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  56043. }
  56044. if (subMeshes.length === 0) {
  56045. if (onCompiled) {
  56046. onCompiled(this);
  56047. }
  56048. return;
  56049. }
  56050. var currentIndex = 0;
  56051. var checkReady = function () {
  56052. if (!_this._scene || !_this._scene.getEngine()) {
  56053. return;
  56054. }
  56055. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  56056. currentIndex++;
  56057. if (currentIndex >= subMeshes.length) {
  56058. if (onCompiled) {
  56059. onCompiled(_this);
  56060. }
  56061. return;
  56062. }
  56063. }
  56064. setTimeout(checkReady, 16);
  56065. };
  56066. checkReady();
  56067. };
  56068. /**
  56069. * Boolean : true when the ShadowGenerator is finally computed.
  56070. */
  56071. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  56072. var defines = [];
  56073. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  56074. defines.push("#define FLOAT");
  56075. }
  56076. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  56077. defines.push("#define ESM");
  56078. }
  56079. var attribs = [BABYLON.VertexBuffer.PositionKind];
  56080. var mesh = subMesh.getMesh();
  56081. var material = subMesh.getMaterial();
  56082. // Alpha test
  56083. if (material && material.needAlphaTesting()) {
  56084. var alphaTexture = material.getAlphaTestTexture();
  56085. if (alphaTexture) {
  56086. defines.push("#define ALPHATEST");
  56087. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  56088. attribs.push(BABYLON.VertexBuffer.UVKind);
  56089. defines.push("#define UV1");
  56090. }
  56091. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  56092. if (alphaTexture.coordinatesIndex === 1) {
  56093. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  56094. defines.push("#define UV2");
  56095. }
  56096. }
  56097. }
  56098. }
  56099. // Bones
  56100. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  56101. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  56102. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  56103. if (mesh.numBoneInfluencers > 4) {
  56104. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  56105. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  56106. }
  56107. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  56108. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  56109. }
  56110. else {
  56111. defines.push("#define NUM_BONE_INFLUENCERS 0");
  56112. }
  56113. // Instances
  56114. if (useInstances) {
  56115. defines.push("#define INSTANCES");
  56116. attribs.push("world0");
  56117. attribs.push("world1");
  56118. attribs.push("world2");
  56119. attribs.push("world3");
  56120. }
  56121. // Get correct effect
  56122. var join = defines.join("\n");
  56123. if (this._cachedDefines !== join) {
  56124. this._cachedDefines = join;
  56125. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  56126. }
  56127. if (!this._effect.isReady()) {
  56128. return false;
  56129. }
  56130. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  56131. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  56132. this._initializeBlurRTTAndPostProcesses();
  56133. }
  56134. }
  56135. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  56136. return false;
  56137. }
  56138. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  56139. return false;
  56140. }
  56141. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  56142. return false;
  56143. }
  56144. return true;
  56145. };
  56146. /**
  56147. * This creates the defines related to the standard BJS materials.
  56148. */
  56149. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  56150. var scene = this._scene;
  56151. var light = this._light;
  56152. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  56153. return;
  56154. }
  56155. defines["SHADOW" + lightIndex] = true;
  56156. if (this.usePoissonSampling) {
  56157. defines["SHADOWPCF" + lightIndex] = true;
  56158. }
  56159. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  56160. defines["SHADOWESM" + lightIndex] = true;
  56161. }
  56162. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  56163. defines["SHADOWCLOSEESM" + lightIndex] = true;
  56164. }
  56165. if (light.needCube()) {
  56166. defines["SHADOWCUBE" + lightIndex] = true;
  56167. }
  56168. };
  56169. /**
  56170. * This binds shadow lights related to the standard BJS materials.
  56171. * It implies the unifroms available on the materials are the standard BJS ones.
  56172. */
  56173. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  56174. var light = this._light;
  56175. var scene = this._scene;
  56176. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  56177. return;
  56178. }
  56179. var camera = scene.activeCamera;
  56180. if (!camera) {
  56181. return;
  56182. }
  56183. var shadowMap = this.getShadowMap();
  56184. if (!shadowMap) {
  56185. return;
  56186. }
  56187. if (!light.needCube()) {
  56188. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  56189. }
  56190. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  56191. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  56192. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  56193. };
  56194. // Methods
  56195. /**
  56196. * Returns a Matrix object : the updated transformation matrix.
  56197. */
  56198. ShadowGenerator.prototype.getTransformMatrix = function () {
  56199. var scene = this._scene;
  56200. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  56201. return this._transformMatrix;
  56202. }
  56203. this._currentRenderID = scene.getRenderId();
  56204. this._currentFaceIndexCache = this._currentFaceIndex;
  56205. var lightPosition = this._light.position;
  56206. if (this._light.computeTransformedInformation()) {
  56207. lightPosition = this._light.transformedPosition;
  56208. }
  56209. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  56210. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  56211. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  56212. }
  56213. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  56214. this._cachedPosition = lightPosition.clone();
  56215. this._cachedDirection = this._lightDirection.clone();
  56216. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  56217. var shadowMap = this.getShadowMap();
  56218. if (shadowMap) {
  56219. var renderList = shadowMap.renderList;
  56220. if (renderList) {
  56221. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  56222. }
  56223. }
  56224. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  56225. }
  56226. return this._transformMatrix;
  56227. };
  56228. ShadowGenerator.prototype.recreateShadowMap = function () {
  56229. var shadowMap = this._shadowMap;
  56230. if (!shadowMap) {
  56231. return;
  56232. }
  56233. // Track render list.
  56234. var renderList = shadowMap.renderList;
  56235. // Clean up existing data.
  56236. this._disposeRTTandPostProcesses();
  56237. // Reinitializes.
  56238. this._initializeGenerator();
  56239. // Reaffect the filter to ensure a correct fallback if necessary.
  56240. this.filter = this.filter;
  56241. // Reaffect the filter.
  56242. this._applyFilterValues();
  56243. // Reaffect Render List.
  56244. this._shadowMap.renderList = renderList;
  56245. };
  56246. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  56247. if (this._shadowMap2) {
  56248. this._shadowMap2.dispose();
  56249. this._shadowMap2 = null;
  56250. }
  56251. if (this._boxBlurPostprocess) {
  56252. this._boxBlurPostprocess.dispose();
  56253. this._boxBlurPostprocess = null;
  56254. }
  56255. if (this._kernelBlurXPostprocess) {
  56256. this._kernelBlurXPostprocess.dispose();
  56257. this._kernelBlurXPostprocess = null;
  56258. }
  56259. if (this._kernelBlurYPostprocess) {
  56260. this._kernelBlurYPostprocess.dispose();
  56261. this._kernelBlurYPostprocess = null;
  56262. }
  56263. this._blurPostProcesses = [];
  56264. };
  56265. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  56266. if (this._shadowMap) {
  56267. this._shadowMap.dispose();
  56268. this._shadowMap = null;
  56269. }
  56270. this._disposeBlurPostProcesses();
  56271. };
  56272. /**
  56273. * Disposes the ShadowGenerator.
  56274. * Returns nothing.
  56275. */
  56276. ShadowGenerator.prototype.dispose = function () {
  56277. this._disposeRTTandPostProcesses();
  56278. if (this._light) {
  56279. this._light._shadowGenerator = null;
  56280. this._light._markMeshesAsLightDirty();
  56281. }
  56282. };
  56283. /**
  56284. * Serializes the ShadowGenerator and returns a serializationObject.
  56285. */
  56286. ShadowGenerator.prototype.serialize = function () {
  56287. var serializationObject = {};
  56288. var shadowMap = this.getShadowMap();
  56289. if (!shadowMap) {
  56290. return serializationObject;
  56291. }
  56292. serializationObject.lightId = this._light.id;
  56293. serializationObject.mapSize = shadowMap.getRenderSize();
  56294. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  56295. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  56296. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  56297. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  56298. serializationObject.usePoissonSampling = this.usePoissonSampling;
  56299. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  56300. serializationObject.depthScale = this.depthScale;
  56301. serializationObject.darkness = this.getDarkness();
  56302. serializationObject.blurBoxOffset = this.blurBoxOffset;
  56303. serializationObject.blurKernel = this.blurKernel;
  56304. serializationObject.blurScale = this.blurScale;
  56305. serializationObject.useKernelBlur = this.useKernelBlur;
  56306. serializationObject.transparencyShadow = this._transparencyShadow;
  56307. serializationObject.renderList = [];
  56308. if (shadowMap.renderList) {
  56309. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  56310. var mesh = shadowMap.renderList[meshIndex];
  56311. serializationObject.renderList.push(mesh.id);
  56312. }
  56313. }
  56314. return serializationObject;
  56315. };
  56316. /**
  56317. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  56318. */
  56319. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  56320. //casting to point light, as light is missing the position attr and typescript complains.
  56321. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  56322. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  56323. var shadowMap = shadowGenerator.getShadowMap();
  56324. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  56325. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  56326. meshes.forEach(function (mesh) {
  56327. if (!shadowMap) {
  56328. return;
  56329. }
  56330. if (!shadowMap.renderList) {
  56331. shadowMap.renderList = [];
  56332. }
  56333. shadowMap.renderList.push(mesh);
  56334. });
  56335. }
  56336. if (parsedShadowGenerator.usePoissonSampling) {
  56337. shadowGenerator.usePoissonSampling = true;
  56338. }
  56339. else if (parsedShadowGenerator.useExponentialShadowMap) {
  56340. shadowGenerator.useExponentialShadowMap = true;
  56341. }
  56342. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  56343. shadowGenerator.useBlurExponentialShadowMap = true;
  56344. }
  56345. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  56346. shadowGenerator.useCloseExponentialShadowMap = true;
  56347. }
  56348. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  56349. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  56350. }
  56351. else if (parsedShadowGenerator.useVarianceShadowMap) {
  56352. shadowGenerator.useExponentialShadowMap = true;
  56353. }
  56354. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  56355. shadowGenerator.useBlurExponentialShadowMap = true;
  56356. }
  56357. if (parsedShadowGenerator.depthScale) {
  56358. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  56359. }
  56360. if (parsedShadowGenerator.blurScale) {
  56361. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  56362. }
  56363. if (parsedShadowGenerator.blurBoxOffset) {
  56364. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  56365. }
  56366. if (parsedShadowGenerator.useKernelBlur) {
  56367. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  56368. }
  56369. if (parsedShadowGenerator.blurKernel) {
  56370. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  56371. }
  56372. if (parsedShadowGenerator.bias !== undefined) {
  56373. shadowGenerator.bias = parsedShadowGenerator.bias;
  56374. }
  56375. if (parsedShadowGenerator.darkness) {
  56376. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  56377. }
  56378. if (parsedShadowGenerator.transparencyShadow) {
  56379. shadowGenerator.setTransparencyShadow(true);
  56380. }
  56381. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  56382. return shadowGenerator;
  56383. };
  56384. ShadowGenerator._FILTER_NONE = 0;
  56385. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  56386. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  56387. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  56388. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  56389. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  56390. return ShadowGenerator;
  56391. }());
  56392. BABYLON.ShadowGenerator = ShadowGenerator;
  56393. })(BABYLON || (BABYLON = {}));
  56394. //# sourceMappingURL=babylon.shadowGenerator.js.map
  56395. var BABYLON;
  56396. (function (BABYLON) {
  56397. var DefaultLoadingScreen = /** @class */ (function () {
  56398. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  56399. if (_loadingText === void 0) { _loadingText = ""; }
  56400. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  56401. var _this = this;
  56402. this._renderingCanvas = _renderingCanvas;
  56403. this._loadingText = _loadingText;
  56404. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  56405. // Resize
  56406. this._resizeLoadingUI = function () {
  56407. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  56408. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  56409. if (!_this._loadingDiv) {
  56410. return;
  56411. }
  56412. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  56413. _this._loadingDiv.style.left = canvasRect.left + "px";
  56414. _this._loadingDiv.style.top = canvasRect.top + "px";
  56415. _this._loadingDiv.style.width = canvasRect.width + "px";
  56416. _this._loadingDiv.style.height = canvasRect.height + "px";
  56417. };
  56418. }
  56419. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  56420. if (this._loadingDiv) {
  56421. // Do not add a loading screen if there is already one
  56422. return;
  56423. }
  56424. this._loadingDiv = document.createElement("div");
  56425. this._loadingDiv.id = "babylonjsLoadingDiv";
  56426. this._loadingDiv.style.opacity = "0";
  56427. this._loadingDiv.style.transition = "opacity 1.5s ease";
  56428. this._loadingDiv.style.pointerEvents = "none";
  56429. // Loading text
  56430. this._loadingTextDiv = document.createElement("div");
  56431. this._loadingTextDiv.style.position = "absolute";
  56432. this._loadingTextDiv.style.left = "0";
  56433. this._loadingTextDiv.style.top = "50%";
  56434. this._loadingTextDiv.style.marginTop = "80px";
  56435. this._loadingTextDiv.style.width = "100%";
  56436. this._loadingTextDiv.style.height = "20px";
  56437. this._loadingTextDiv.style.fontFamily = "Arial";
  56438. this._loadingTextDiv.style.fontSize = "14px";
  56439. this._loadingTextDiv.style.color = "white";
  56440. this._loadingTextDiv.style.textAlign = "center";
  56441. this._loadingTextDiv.innerHTML = "Loading";
  56442. this._loadingDiv.appendChild(this._loadingTextDiv);
  56443. //set the predefined text
  56444. this._loadingTextDiv.innerHTML = this._loadingText;
  56445. // Generating keyframes
  56446. var style = document.createElement('style');
  56447. style.type = 'text/css';
  56448. 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 }";
  56449. style.innerHTML = keyFrames;
  56450. document.getElementsByTagName('head')[0].appendChild(style);
  56451. // Loading img
  56452. var imgBack = new Image();
  56453. 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";
  56454. imgBack.style.position = "absolute";
  56455. imgBack.style.left = "50%";
  56456. imgBack.style.top = "50%";
  56457. imgBack.style.marginLeft = "-60px";
  56458. imgBack.style.marginTop = "-60px";
  56459. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  56460. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  56461. imgBack.style.transformOrigin = "50% 50%";
  56462. imgBack.style.webkitTransformOrigin = "50% 50%";
  56463. this._loadingDiv.appendChild(imgBack);
  56464. this._resizeLoadingUI();
  56465. window.addEventListener("resize", this._resizeLoadingUI);
  56466. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  56467. document.body.appendChild(this._loadingDiv);
  56468. this._loadingDiv.style.opacity = "1";
  56469. };
  56470. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  56471. var _this = this;
  56472. if (!this._loadingDiv) {
  56473. return;
  56474. }
  56475. var onTransitionEnd = function () {
  56476. if (!_this._loadingDiv) {
  56477. return;
  56478. }
  56479. document.body.removeChild(_this._loadingDiv);
  56480. window.removeEventListener("resize", _this._resizeLoadingUI);
  56481. _this._loadingDiv = null;
  56482. };
  56483. this._loadingDiv.style.opacity = "0";
  56484. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  56485. };
  56486. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  56487. set: function (text) {
  56488. this._loadingText = text;
  56489. if (this._loadingTextDiv) {
  56490. this._loadingTextDiv.innerHTML = this._loadingText;
  56491. }
  56492. },
  56493. enumerable: true,
  56494. configurable: true
  56495. });
  56496. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  56497. get: function () {
  56498. return this._loadingDivBackgroundColor;
  56499. },
  56500. set: function (color) {
  56501. this._loadingDivBackgroundColor = color;
  56502. if (!this._loadingDiv) {
  56503. return;
  56504. }
  56505. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  56506. },
  56507. enumerable: true,
  56508. configurable: true
  56509. });
  56510. return DefaultLoadingScreen;
  56511. }());
  56512. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  56513. })(BABYLON || (BABYLON = {}));
  56514. //# sourceMappingURL=babylon.loadingScreen.js.map
  56515. var BABYLON;
  56516. (function (BABYLON) {
  56517. var SceneLoaderProgressEvent = /** @class */ (function () {
  56518. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  56519. this.lengthComputable = lengthComputable;
  56520. this.loaded = loaded;
  56521. this.total = total;
  56522. }
  56523. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  56524. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  56525. };
  56526. return SceneLoaderProgressEvent;
  56527. }());
  56528. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  56529. var SceneLoader = /** @class */ (function () {
  56530. function SceneLoader() {
  56531. }
  56532. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  56533. get: function () {
  56534. return 0;
  56535. },
  56536. enumerable: true,
  56537. configurable: true
  56538. });
  56539. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  56540. get: function () {
  56541. return 1;
  56542. },
  56543. enumerable: true,
  56544. configurable: true
  56545. });
  56546. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  56547. get: function () {
  56548. return 2;
  56549. },
  56550. enumerable: true,
  56551. configurable: true
  56552. });
  56553. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  56554. get: function () {
  56555. return 3;
  56556. },
  56557. enumerable: true,
  56558. configurable: true
  56559. });
  56560. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  56561. get: function () {
  56562. return SceneLoader._ForceFullSceneLoadingForIncremental;
  56563. },
  56564. set: function (value) {
  56565. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  56566. },
  56567. enumerable: true,
  56568. configurable: true
  56569. });
  56570. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  56571. get: function () {
  56572. return SceneLoader._ShowLoadingScreen;
  56573. },
  56574. set: function (value) {
  56575. SceneLoader._ShowLoadingScreen = value;
  56576. },
  56577. enumerable: true,
  56578. configurable: true
  56579. });
  56580. Object.defineProperty(SceneLoader, "loggingLevel", {
  56581. get: function () {
  56582. return SceneLoader._loggingLevel;
  56583. },
  56584. set: function (value) {
  56585. SceneLoader._loggingLevel = value;
  56586. },
  56587. enumerable: true,
  56588. configurable: true
  56589. });
  56590. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  56591. get: function () {
  56592. return SceneLoader._CleanBoneMatrixWeights;
  56593. },
  56594. set: function (value) {
  56595. SceneLoader._CleanBoneMatrixWeights = value;
  56596. },
  56597. enumerable: true,
  56598. configurable: true
  56599. });
  56600. SceneLoader._getDefaultPlugin = function () {
  56601. return SceneLoader._registeredPlugins[".babylon"];
  56602. };
  56603. SceneLoader._getPluginForExtension = function (extension) {
  56604. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  56605. if (registeredPlugin) {
  56606. return registeredPlugin;
  56607. }
  56608. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  56609. return SceneLoader._getDefaultPlugin();
  56610. };
  56611. SceneLoader._getPluginForDirectLoad = function (data) {
  56612. for (var extension in SceneLoader._registeredPlugins) {
  56613. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  56614. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  56615. return SceneLoader._registeredPlugins[extension];
  56616. }
  56617. }
  56618. return SceneLoader._getDefaultPlugin();
  56619. };
  56620. SceneLoader._getPluginForFilename = function (sceneFilename) {
  56621. if (sceneFilename.name) {
  56622. sceneFilename = sceneFilename.name;
  56623. }
  56624. var queryStringPosition = sceneFilename.indexOf("?");
  56625. if (queryStringPosition !== -1) {
  56626. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  56627. }
  56628. var dotPosition = sceneFilename.lastIndexOf(".");
  56629. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  56630. return SceneLoader._getPluginForExtension(extension);
  56631. };
  56632. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  56633. SceneLoader._getDirectLoad = function (sceneFilename) {
  56634. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  56635. return sceneFilename.substr(5);
  56636. }
  56637. return null;
  56638. };
  56639. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  56640. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  56641. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  56642. var plugin;
  56643. if (registeredPlugin.plugin.createPlugin) {
  56644. plugin = registeredPlugin.plugin.createPlugin();
  56645. }
  56646. else {
  56647. plugin = registeredPlugin.plugin;
  56648. }
  56649. var useArrayBuffer = registeredPlugin.isBinary;
  56650. var database;
  56651. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  56652. var dataCallback = function (data, responseURL) {
  56653. if (scene.isDisposed) {
  56654. onError("Scene has been disposed");
  56655. return;
  56656. }
  56657. scene.database = database;
  56658. onSuccess(plugin, data, responseURL);
  56659. };
  56660. var request = null;
  56661. var pluginDisposed = false;
  56662. var onDisposeObservable = plugin.onDisposeObservable;
  56663. if (onDisposeObservable) {
  56664. onDisposeObservable.add(function () {
  56665. pluginDisposed = true;
  56666. if (request) {
  56667. request.abort();
  56668. request = null;
  56669. }
  56670. onDispose();
  56671. });
  56672. }
  56673. var manifestChecked = function () {
  56674. if (pluginDisposed) {
  56675. return;
  56676. }
  56677. var url = rootUrl + sceneFilename;
  56678. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  56679. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  56680. } : undefined, database, useArrayBuffer, function (request, exception) {
  56681. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  56682. });
  56683. };
  56684. if (directLoad) {
  56685. dataCallback(directLoad);
  56686. return plugin;
  56687. }
  56688. if (rootUrl.indexOf("file:") === -1) {
  56689. if (scene.getEngine().enableOfflineSupport) {
  56690. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  56691. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  56692. }
  56693. else {
  56694. manifestChecked();
  56695. }
  56696. }
  56697. else {
  56698. var fileOrString = sceneFilename;
  56699. if (fileOrString.name) {
  56700. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  56701. }
  56702. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  56703. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  56704. }
  56705. else {
  56706. onError("Unable to find file named " + sceneFilename);
  56707. }
  56708. }
  56709. return plugin;
  56710. };
  56711. // Public functions
  56712. SceneLoader.GetPluginForExtension = function (extension) {
  56713. return SceneLoader._getPluginForExtension(extension).plugin;
  56714. };
  56715. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  56716. return !!SceneLoader._registeredPlugins[extension];
  56717. };
  56718. SceneLoader.RegisterPlugin = function (plugin) {
  56719. if (typeof plugin.extensions === "string") {
  56720. var extension = plugin.extensions;
  56721. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  56722. plugin: plugin,
  56723. isBinary: false
  56724. };
  56725. }
  56726. else {
  56727. var extensions = plugin.extensions;
  56728. Object.keys(extensions).forEach(function (extension) {
  56729. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  56730. plugin: plugin,
  56731. isBinary: extensions[extension].isBinary
  56732. };
  56733. });
  56734. }
  56735. };
  56736. /**
  56737. * Import meshes into a scene
  56738. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  56739. * @param rootUrl a string that defines the root url for scene and resources
  56740. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  56741. * @param scene the instance of BABYLON.Scene to append to
  56742. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  56743. * @param onProgress a callback with a progress event for each file being loaded
  56744. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  56745. */
  56746. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  56747. if (onSuccess === void 0) { onSuccess = null; }
  56748. if (onProgress === void 0) { onProgress = null; }
  56749. if (onError === void 0) { onError = null; }
  56750. if (pluginExtension === void 0) { pluginExtension = null; }
  56751. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  56752. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  56753. return null;
  56754. }
  56755. var loadingToken = {};
  56756. scene._addPendingData(loadingToken);
  56757. var disposeHandler = function () {
  56758. scene._removePendingData(loadingToken);
  56759. };
  56760. var errorHandler = function (message, exception) {
  56761. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  56762. if (onError) {
  56763. onError(scene, errorMessage, exception);
  56764. }
  56765. else {
  56766. BABYLON.Tools.Error(errorMessage);
  56767. // should the exception be thrown?
  56768. }
  56769. disposeHandler();
  56770. };
  56771. var progressHandler = onProgress ? function (event) {
  56772. try {
  56773. onProgress(event);
  56774. }
  56775. catch (e) {
  56776. errorHandler("Error in onProgress callback", e);
  56777. }
  56778. } : undefined;
  56779. var successHandler = function (meshes, particleSystems, skeletons) {
  56780. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  56781. if (onSuccess) {
  56782. try {
  56783. onSuccess(meshes, particleSystems, skeletons);
  56784. }
  56785. catch (e) {
  56786. errorHandler("Error in onSuccess callback", e);
  56787. }
  56788. }
  56789. scene._removePendingData(loadingToken);
  56790. };
  56791. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  56792. if (plugin.rewriteRootURL) {
  56793. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  56794. }
  56795. if (plugin.importMesh) {
  56796. var syncedPlugin = plugin;
  56797. var meshes = new Array();
  56798. var particleSystems = new Array();
  56799. var skeletons = new Array();
  56800. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  56801. return;
  56802. }
  56803. scene.loadingPluginName = plugin.name;
  56804. successHandler(meshes, particleSystems, skeletons);
  56805. }
  56806. else {
  56807. var asyncedPlugin = plugin;
  56808. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  56809. scene.loadingPluginName = plugin.name;
  56810. successHandler(meshes, particleSystems, skeletons);
  56811. }, progressHandler, errorHandler);
  56812. }
  56813. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  56814. };
  56815. /**
  56816. * Load a scene
  56817. * @param rootUrl a string that defines the root url for scene and resources
  56818. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  56819. * @param engine is the instance of BABYLON.Engine to use to create the scene
  56820. * @param onSuccess a callback with the scene when import succeeds
  56821. * @param onProgress a callback with a progress event for each file being loaded
  56822. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  56823. */
  56824. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  56825. if (onSuccess === void 0) { onSuccess = null; }
  56826. if (onProgress === void 0) { onProgress = null; }
  56827. if (onError === void 0) { onError = null; }
  56828. if (pluginExtension === void 0) { pluginExtension = null; }
  56829. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  56830. };
  56831. /**
  56832. * Append a scene
  56833. * @param rootUrl a string that defines the root url for scene and resources
  56834. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  56835. * @param scene is the instance of BABYLON.Scene to append to
  56836. * @param onSuccess a callback with the scene when import succeeds
  56837. * @param onProgress a callback with a progress event for each file being loaded
  56838. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  56839. */
  56840. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  56841. if (onSuccess === void 0) { onSuccess = null; }
  56842. if (onProgress === void 0) { onProgress = null; }
  56843. if (onError === void 0) { onError = null; }
  56844. if (pluginExtension === void 0) { pluginExtension = null; }
  56845. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  56846. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  56847. return null;
  56848. }
  56849. if (SceneLoader.ShowLoadingScreen) {
  56850. scene.getEngine().displayLoadingUI();
  56851. }
  56852. var loadingToken = {};
  56853. scene._addPendingData(loadingToken);
  56854. var disposeHandler = function () {
  56855. scene._removePendingData(loadingToken);
  56856. scene.getEngine().hideLoadingUI();
  56857. };
  56858. var errorHandler = function (message, exception) {
  56859. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  56860. if (onError) {
  56861. onError(scene, errorMessage, exception);
  56862. }
  56863. else {
  56864. BABYLON.Tools.Error(errorMessage);
  56865. // should the exception be thrown?
  56866. }
  56867. disposeHandler();
  56868. };
  56869. var progressHandler = onProgress ? function (event) {
  56870. try {
  56871. onProgress(event);
  56872. }
  56873. catch (e) {
  56874. errorHandler("Error in onProgress callback", e);
  56875. }
  56876. } : undefined;
  56877. var successHandler = function () {
  56878. if (onSuccess) {
  56879. try {
  56880. onSuccess(scene);
  56881. }
  56882. catch (e) {
  56883. errorHandler("Error in onSuccess callback", e);
  56884. }
  56885. }
  56886. scene._removePendingData(loadingToken);
  56887. };
  56888. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  56889. if (plugin.load) {
  56890. var syncedPlugin = plugin;
  56891. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  56892. return;
  56893. }
  56894. scene.loadingPluginName = plugin.name;
  56895. successHandler();
  56896. }
  56897. else {
  56898. var asyncedPlugin = plugin;
  56899. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  56900. scene.loadingPluginName = plugin.name;
  56901. successHandler();
  56902. }, progressHandler, errorHandler);
  56903. }
  56904. if (SceneLoader.ShowLoadingScreen) {
  56905. scene.executeWhenReady(function () {
  56906. scene.getEngine().hideLoadingUI();
  56907. });
  56908. }
  56909. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  56910. };
  56911. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  56912. if (onSuccess === void 0) { onSuccess = null; }
  56913. if (onProgress === void 0) { onProgress = null; }
  56914. if (onError === void 0) { onError = null; }
  56915. if (pluginExtension === void 0) { pluginExtension = null; }
  56916. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  56917. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  56918. return null;
  56919. }
  56920. var loadingToken = {};
  56921. scene._addPendingData(loadingToken);
  56922. var disposeHandler = function () {
  56923. scene._removePendingData(loadingToken);
  56924. };
  56925. var errorHandler = function (message, exception) {
  56926. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  56927. if (onError) {
  56928. onError(scene, errorMessage, exception);
  56929. }
  56930. else {
  56931. BABYLON.Tools.Error(errorMessage);
  56932. // should the exception be thrown?
  56933. }
  56934. disposeHandler();
  56935. };
  56936. var progressHandler = onProgress ? function (event) {
  56937. try {
  56938. onProgress(event);
  56939. }
  56940. catch (e) {
  56941. errorHandler("Error in onProgress callback", e);
  56942. }
  56943. } : undefined;
  56944. var successHandler = function (assets) {
  56945. if (onSuccess) {
  56946. try {
  56947. onSuccess(assets);
  56948. }
  56949. catch (e) {
  56950. errorHandler("Error in onSuccess callback", e);
  56951. }
  56952. }
  56953. scene._removePendingData(loadingToken);
  56954. };
  56955. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  56956. if (plugin.loadAssets) {
  56957. var syncedPlugin = plugin;
  56958. var assetContainer = syncedPlugin.loadAssets(scene, data, rootUrl, errorHandler);
  56959. if (!assetContainer) {
  56960. return;
  56961. }
  56962. scene.loadingPluginName = plugin.name;
  56963. successHandler(assetContainer);
  56964. }
  56965. else if (plugin.loadAssetsAsync) {
  56966. var asyncedPlugin = plugin;
  56967. asyncedPlugin.loadAssetsAsync(scene, data, rootUrl, function (assetContainer) {
  56968. if (assetContainer) {
  56969. scene.loadingPluginName = plugin.name;
  56970. successHandler(assetContainer);
  56971. }
  56972. }, progressHandler, errorHandler);
  56973. }
  56974. else {
  56975. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssets or loadAssetsAsync method.");
  56976. }
  56977. if (SceneLoader.ShowLoadingScreen) {
  56978. scene.executeWhenReady(function () {
  56979. scene.getEngine().hideLoadingUI();
  56980. });
  56981. }
  56982. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  56983. };
  56984. // Flags
  56985. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  56986. SceneLoader._ShowLoadingScreen = true;
  56987. SceneLoader._CleanBoneMatrixWeights = false;
  56988. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  56989. // Members
  56990. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  56991. SceneLoader._registeredPlugins = {};
  56992. return SceneLoader;
  56993. }());
  56994. BABYLON.SceneLoader = SceneLoader;
  56995. ;
  56996. })(BABYLON || (BABYLON = {}));
  56997. //# sourceMappingURL=babylon.sceneLoader.js.map
  56998. var BABYLON;
  56999. (function (BABYLON) {
  57000. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  57001. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  57002. var parsedMaterial = parsedData.materials[index];
  57003. if (parsedMaterial.id === id) {
  57004. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  57005. }
  57006. }
  57007. return null;
  57008. };
  57009. var isDescendantOf = function (mesh, names, hierarchyIds) {
  57010. for (var i in names) {
  57011. if (mesh.name === names[i]) {
  57012. hierarchyIds.push(mesh.id);
  57013. return true;
  57014. }
  57015. }
  57016. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  57017. hierarchyIds.push(mesh.id);
  57018. return true;
  57019. }
  57020. return false;
  57021. };
  57022. var logOperation = function (operation, producer) {
  57023. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  57024. };
  57025. var loadAssets = function (scene, data, rootUrl, onError, addToScene) {
  57026. if (addToScene === void 0) { addToScene = false; }
  57027. var container = new BABYLON.AssetContainer(scene);
  57028. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  57029. // when SceneLoader.debugLogging = true (default), or exception encountered.
  57030. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  57031. // and avoid problems with multiple concurrent .babylon loads.
  57032. var log = "importScene has failed JSON parse";
  57033. try {
  57034. var parsedData = JSON.parse(data);
  57035. log = "";
  57036. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  57037. var index;
  57038. var cache;
  57039. // Lights
  57040. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  57041. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  57042. var parsedLight = parsedData.lights[index];
  57043. var light = BABYLON.Light.Parse(parsedLight, scene);
  57044. if (light) {
  57045. container.lights.push(light);
  57046. log += (index === 0 ? "\n\tLights:" : "");
  57047. log += "\n\t\t" + light.toString(fullDetails);
  57048. }
  57049. }
  57050. }
  57051. // Animations
  57052. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  57053. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  57054. var parsedAnimation = parsedData.animations[index];
  57055. var animation = BABYLON.Animation.Parse(parsedAnimation);
  57056. scene.animations.push(animation);
  57057. container.animations.push(animation);
  57058. log += (index === 0 ? "\n\tAnimations:" : "");
  57059. log += "\n\t\t" + animation.toString(fullDetails);
  57060. }
  57061. }
  57062. // Materials
  57063. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  57064. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  57065. var parsedMaterial = parsedData.materials[index];
  57066. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  57067. container.materials.push(mat);
  57068. log += (index === 0 ? "\n\tMaterials:" : "");
  57069. log += "\n\t\t" + mat.toString(fullDetails);
  57070. }
  57071. }
  57072. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  57073. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  57074. var parsedMultiMaterial = parsedData.multiMaterials[index];
  57075. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  57076. container.multiMaterials.push(mmat);
  57077. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  57078. log += "\n\t\t" + mmat.toString(fullDetails);
  57079. }
  57080. }
  57081. // Morph targets
  57082. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  57083. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  57084. var managerData = _a[_i];
  57085. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  57086. }
  57087. }
  57088. // Skeletons
  57089. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  57090. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  57091. var parsedSkeleton = parsedData.skeletons[index];
  57092. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  57093. container.skeletons.push(skeleton);
  57094. log += (index === 0 ? "\n\tSkeletons:" : "");
  57095. log += "\n\t\t" + skeleton.toString(fullDetails);
  57096. }
  57097. }
  57098. // Geometries
  57099. var geometries = parsedData.geometries;
  57100. if (geometries !== undefined && geometries !== null) {
  57101. var addedGeometry = new Array();
  57102. // Boxes
  57103. var boxes = geometries.boxes;
  57104. if (boxes !== undefined && boxes !== null) {
  57105. for (index = 0, cache = boxes.length; index < cache; index++) {
  57106. var parsedBox = boxes[index];
  57107. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  57108. }
  57109. }
  57110. // Spheres
  57111. var spheres = geometries.spheres;
  57112. if (spheres !== undefined && spheres !== null) {
  57113. for (index = 0, cache = spheres.length; index < cache; index++) {
  57114. var parsedSphere = spheres[index];
  57115. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  57116. }
  57117. }
  57118. // Cylinders
  57119. var cylinders = geometries.cylinders;
  57120. if (cylinders !== undefined && cylinders !== null) {
  57121. for (index = 0, cache = cylinders.length; index < cache; index++) {
  57122. var parsedCylinder = cylinders[index];
  57123. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  57124. }
  57125. }
  57126. // Toruses
  57127. var toruses = geometries.toruses;
  57128. if (toruses !== undefined && toruses !== null) {
  57129. for (index = 0, cache = toruses.length; index < cache; index++) {
  57130. var parsedTorus = toruses[index];
  57131. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  57132. }
  57133. }
  57134. // Grounds
  57135. var grounds = geometries.grounds;
  57136. if (grounds !== undefined && grounds !== null) {
  57137. for (index = 0, cache = grounds.length; index < cache; index++) {
  57138. var parsedGround = grounds[index];
  57139. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  57140. }
  57141. }
  57142. // Planes
  57143. var planes = geometries.planes;
  57144. if (planes !== undefined && planes !== null) {
  57145. for (index = 0, cache = planes.length; index < cache; index++) {
  57146. var parsedPlane = planes[index];
  57147. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  57148. }
  57149. }
  57150. // TorusKnots
  57151. var torusKnots = geometries.torusKnots;
  57152. if (torusKnots !== undefined && torusKnots !== null) {
  57153. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  57154. var parsedTorusKnot = torusKnots[index];
  57155. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  57156. }
  57157. }
  57158. // VertexData
  57159. var vertexData = geometries.vertexData;
  57160. if (vertexData !== undefined && vertexData !== null) {
  57161. for (index = 0, cache = vertexData.length; index < cache; index++) {
  57162. var parsedVertexData = vertexData[index];
  57163. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  57164. }
  57165. }
  57166. addedGeometry.forEach(function (g) {
  57167. if (g) {
  57168. container.geometries.push(g);
  57169. }
  57170. });
  57171. }
  57172. // Transform nodes
  57173. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  57174. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  57175. var parsedTransformNode = parsedData.transformNodes[index];
  57176. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  57177. container.transformNodes.push(node);
  57178. }
  57179. }
  57180. // Meshes
  57181. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  57182. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  57183. var parsedMesh = parsedData.meshes[index];
  57184. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  57185. container.meshes.push(mesh);
  57186. log += (index === 0 ? "\n\tMeshes:" : "");
  57187. log += "\n\t\t" + mesh.toString(fullDetails);
  57188. }
  57189. }
  57190. // Cameras
  57191. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  57192. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  57193. var parsedCamera = parsedData.cameras[index];
  57194. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  57195. container.cameras.push(camera);
  57196. log += (index === 0 ? "\n\tCameras:" : "");
  57197. log += "\n\t\t" + camera.toString(fullDetails);
  57198. }
  57199. }
  57200. // Browsing all the graph to connect the dots
  57201. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  57202. var camera = scene.cameras[index];
  57203. if (camera._waitingParentId) {
  57204. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  57205. camera._waitingParentId = null;
  57206. }
  57207. }
  57208. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  57209. var light_1 = scene.lights[index];
  57210. if (light_1 && light_1._waitingParentId) {
  57211. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  57212. light_1._waitingParentId = null;
  57213. }
  57214. }
  57215. // Sounds
  57216. // TODO: add sound
  57217. var loadedSounds = [];
  57218. var loadedSound;
  57219. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  57220. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  57221. var parsedSound = parsedData.sounds[index];
  57222. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57223. if (!parsedSound.url)
  57224. parsedSound.url = parsedSound.name;
  57225. if (!loadedSounds[parsedSound.url]) {
  57226. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  57227. loadedSounds[parsedSound.url] = loadedSound;
  57228. container.sounds.push(loadedSound);
  57229. }
  57230. else {
  57231. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  57232. }
  57233. }
  57234. else {
  57235. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  57236. }
  57237. }
  57238. }
  57239. loadedSounds = [];
  57240. // Connect parents & children and parse actions
  57241. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  57242. var transformNode = scene.transformNodes[index];
  57243. if (transformNode._waitingParentId) {
  57244. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  57245. transformNode._waitingParentId = null;
  57246. }
  57247. }
  57248. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  57249. var mesh = scene.meshes[index];
  57250. if (mesh._waitingParentId) {
  57251. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  57252. mesh._waitingParentId = null;
  57253. }
  57254. if (mesh._waitingActions) {
  57255. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  57256. mesh._waitingActions = null;
  57257. }
  57258. }
  57259. // freeze world matrix application
  57260. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  57261. var currentMesh = scene.meshes[index];
  57262. if (currentMesh._waitingFreezeWorldMatrix) {
  57263. currentMesh.freezeWorldMatrix();
  57264. currentMesh._waitingFreezeWorldMatrix = null;
  57265. }
  57266. else {
  57267. currentMesh.computeWorldMatrix(true);
  57268. }
  57269. }
  57270. // Particles Systems
  57271. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  57272. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  57273. var parsedParticleSystem = parsedData.particleSystems[index];
  57274. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  57275. container.particleSystems.push(ps);
  57276. }
  57277. }
  57278. // Lens flares
  57279. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  57280. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  57281. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  57282. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  57283. container.lensFlareSystems.push(lf);
  57284. }
  57285. }
  57286. // Shadows
  57287. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  57288. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  57289. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  57290. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  57291. container.shadowGenerators.push(sg);
  57292. }
  57293. }
  57294. // Lights exclusions / inclusions
  57295. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  57296. var light_2 = scene.lights[index];
  57297. // Excluded check
  57298. if (light_2._excludedMeshesIds.length > 0) {
  57299. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  57300. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  57301. if (excludedMesh) {
  57302. light_2.excludedMeshes.push(excludedMesh);
  57303. }
  57304. }
  57305. light_2._excludedMeshesIds = [];
  57306. }
  57307. // Included check
  57308. if (light_2._includedOnlyMeshesIds.length > 0) {
  57309. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  57310. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  57311. if (includedOnlyMesh) {
  57312. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  57313. }
  57314. }
  57315. light_2._includedOnlyMeshesIds = [];
  57316. }
  57317. }
  57318. // Actions (scene)
  57319. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  57320. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  57321. }
  57322. if (!addToScene) {
  57323. container.removeAllFromScene();
  57324. }
  57325. return container;
  57326. }
  57327. catch (err) {
  57328. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  57329. if (onError) {
  57330. onError(msg, err);
  57331. }
  57332. else {
  57333. BABYLON.Tools.Log(msg);
  57334. throw err;
  57335. }
  57336. }
  57337. finally {
  57338. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  57339. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  57340. }
  57341. }
  57342. return null;
  57343. };
  57344. BABYLON.SceneLoader.RegisterPlugin({
  57345. name: "babylon.js",
  57346. extensions: ".babylon",
  57347. canDirectLoad: function (data) {
  57348. if (data.indexOf("babylon") !== -1) {
  57349. return true;
  57350. }
  57351. return false;
  57352. },
  57353. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  57354. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  57355. // when SceneLoader.debugLogging = true (default), or exception encountered.
  57356. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  57357. // and avoid problems with multiple concurrent .babylon loads.
  57358. var log = "importMesh has failed JSON parse";
  57359. try {
  57360. var parsedData = JSON.parse(data);
  57361. log = "";
  57362. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  57363. if (!meshesNames) {
  57364. meshesNames = null;
  57365. }
  57366. else if (!Array.isArray(meshesNames)) {
  57367. meshesNames = [meshesNames];
  57368. }
  57369. var hierarchyIds = new Array();
  57370. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  57371. var loadedSkeletonsIds = [];
  57372. var loadedMaterialsIds = [];
  57373. var index;
  57374. var cache;
  57375. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  57376. var parsedMesh = parsedData.meshes[index];
  57377. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  57378. if (meshesNames !== null) {
  57379. // Remove found mesh name from list.
  57380. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  57381. }
  57382. //Geometry?
  57383. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  57384. //does the file contain geometries?
  57385. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  57386. //find the correct geometry and add it to the scene
  57387. var found = false;
  57388. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  57389. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  57390. return;
  57391. }
  57392. else {
  57393. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  57394. if (parsedGeometryData.id === parsedMesh.geometryId) {
  57395. switch (geometryType) {
  57396. case "boxes":
  57397. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  57398. break;
  57399. case "spheres":
  57400. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  57401. break;
  57402. case "cylinders":
  57403. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  57404. break;
  57405. case "toruses":
  57406. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  57407. break;
  57408. case "grounds":
  57409. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  57410. break;
  57411. case "planes":
  57412. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  57413. break;
  57414. case "torusKnots":
  57415. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  57416. break;
  57417. case "vertexData":
  57418. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  57419. break;
  57420. }
  57421. found = true;
  57422. }
  57423. });
  57424. }
  57425. });
  57426. if (found === false) {
  57427. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  57428. }
  57429. }
  57430. }
  57431. // Material ?
  57432. if (parsedMesh.materialId) {
  57433. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  57434. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  57435. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  57436. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  57437. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  57438. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  57439. var subMatId = parsedMultiMaterial.materials[matIndex];
  57440. loadedMaterialsIds.push(subMatId);
  57441. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  57442. log += "\n\tMaterial " + mat.toString(fullDetails);
  57443. }
  57444. loadedMaterialsIds.push(parsedMultiMaterial.id);
  57445. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  57446. materialFound = true;
  57447. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  57448. break;
  57449. }
  57450. }
  57451. }
  57452. if (materialFound === false) {
  57453. loadedMaterialsIds.push(parsedMesh.materialId);
  57454. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  57455. if (!mat) {
  57456. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  57457. }
  57458. else {
  57459. log += "\n\tMaterial " + mat.toString(fullDetails);
  57460. }
  57461. }
  57462. }
  57463. // Skeleton ?
  57464. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  57465. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  57466. if (skeletonAlreadyLoaded === false) {
  57467. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  57468. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  57469. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  57470. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  57471. skeletons.push(skeleton);
  57472. loadedSkeletonsIds.push(parsedSkeleton.id);
  57473. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  57474. }
  57475. }
  57476. }
  57477. }
  57478. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  57479. meshes.push(mesh);
  57480. log += "\n\tMesh " + mesh.toString(fullDetails);
  57481. }
  57482. }
  57483. // Connecting parents
  57484. var currentMesh;
  57485. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  57486. currentMesh = scene.meshes[index];
  57487. if (currentMesh._waitingParentId) {
  57488. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  57489. currentMesh._waitingParentId = null;
  57490. }
  57491. }
  57492. // freeze and compute world matrix application
  57493. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  57494. currentMesh = scene.meshes[index];
  57495. if (currentMesh._waitingFreezeWorldMatrix) {
  57496. currentMesh.freezeWorldMatrix();
  57497. currentMesh._waitingFreezeWorldMatrix = null;
  57498. }
  57499. else {
  57500. currentMesh.computeWorldMatrix(true);
  57501. }
  57502. }
  57503. }
  57504. // Particles
  57505. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  57506. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  57507. var parsedParticleSystem = parsedData.particleSystems[index];
  57508. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  57509. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  57510. }
  57511. }
  57512. }
  57513. return true;
  57514. }
  57515. catch (err) {
  57516. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  57517. if (onError) {
  57518. onError(msg, err);
  57519. }
  57520. else {
  57521. BABYLON.Tools.Log(msg);
  57522. throw err;
  57523. }
  57524. }
  57525. finally {
  57526. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  57527. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  57528. }
  57529. }
  57530. return false;
  57531. },
  57532. load: function (scene, data, rootUrl, onError) {
  57533. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  57534. // when SceneLoader.debugLogging = true (default), or exception encountered.
  57535. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  57536. // and avoid problems with multiple concurrent .babylon loads.
  57537. var log = "importScene has failed JSON parse";
  57538. try {
  57539. var parsedData = JSON.parse(data);
  57540. log = "";
  57541. // Scene
  57542. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  57543. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  57544. }
  57545. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  57546. scene.autoClear = parsedData.autoClear;
  57547. }
  57548. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  57549. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  57550. }
  57551. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  57552. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  57553. }
  57554. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  57555. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  57556. }
  57557. // Fog
  57558. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  57559. scene.fogMode = parsedData.fogMode;
  57560. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  57561. scene.fogStart = parsedData.fogStart;
  57562. scene.fogEnd = parsedData.fogEnd;
  57563. scene.fogDensity = parsedData.fogDensity;
  57564. log += "\tFog mode for scene: ";
  57565. switch (scene.fogMode) {
  57566. // getters not compiling, so using hardcoded
  57567. case 1:
  57568. log += "exp\n";
  57569. break;
  57570. case 2:
  57571. log += "exp2\n";
  57572. break;
  57573. case 3:
  57574. log += "linear\n";
  57575. break;
  57576. }
  57577. }
  57578. //Physics
  57579. if (parsedData.physicsEnabled) {
  57580. var physicsPlugin;
  57581. if (parsedData.physicsEngine === "cannon") {
  57582. physicsPlugin = new BABYLON.CannonJSPlugin();
  57583. }
  57584. else if (parsedData.physicsEngine === "oimo") {
  57585. physicsPlugin = new BABYLON.OimoJSPlugin();
  57586. }
  57587. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  57588. //else - default engine, which is currently oimo
  57589. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  57590. scene.enablePhysics(physicsGravity, physicsPlugin);
  57591. }
  57592. // Metadata
  57593. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  57594. scene.metadata = parsedData.metadata;
  57595. }
  57596. //collisions, if defined. otherwise, default is true
  57597. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  57598. scene.collisionsEnabled = parsedData.collisionsEnabled;
  57599. }
  57600. scene.workerCollisions = !!parsedData.workerCollisions;
  57601. var container = loadAssets(scene, data, rootUrl, onerror, true);
  57602. if (!container) {
  57603. return false;
  57604. }
  57605. if (parsedData.autoAnimate) {
  57606. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  57607. }
  57608. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  57609. scene.setActiveCameraByID(parsedData.activeCameraID);
  57610. }
  57611. // Environment texture
  57612. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  57613. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  57614. if (parsedData.createDefaultSkybox === true) {
  57615. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  57616. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  57617. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  57618. }
  57619. }
  57620. // Finish
  57621. return true;
  57622. }
  57623. catch (err) {
  57624. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  57625. if (onError) {
  57626. onError(msg, err);
  57627. }
  57628. else {
  57629. BABYLON.Tools.Log(msg);
  57630. throw err;
  57631. }
  57632. }
  57633. finally {
  57634. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  57635. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  57636. }
  57637. }
  57638. return false;
  57639. },
  57640. loadAssets: function (scene, data, rootUrl, onError) {
  57641. var container = loadAssets(scene, data, rootUrl, onerror);
  57642. return container;
  57643. }
  57644. });
  57645. })(BABYLON || (BABYLON = {}));
  57646. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  57647. var BABYLON;
  57648. (function (BABYLON) {
  57649. var FilesInput = /** @class */ (function () {
  57650. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  57651. this.onProcessFileCallback = function () { return true; };
  57652. this._engine = engine;
  57653. this._currentScene = scene;
  57654. this._sceneLoadedCallback = sceneLoadedCallback;
  57655. this._progressCallback = progressCallback;
  57656. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  57657. this._textureLoadingCallback = textureLoadingCallback;
  57658. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  57659. this._onReloadCallback = onReloadCallback;
  57660. this._errorCallback = errorCallback;
  57661. }
  57662. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  57663. var _this = this;
  57664. if (elementToMonitor) {
  57665. this._elementToMonitor = elementToMonitor;
  57666. this._dragEnterHandler = function (e) { _this.drag(e); };
  57667. this._dragOverHandler = function (e) { _this.drag(e); };
  57668. this._dropHandler = function (e) { _this.drop(e); };
  57669. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  57670. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  57671. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  57672. }
  57673. };
  57674. FilesInput.prototype.dispose = function () {
  57675. if (!this._elementToMonitor) {
  57676. return;
  57677. }
  57678. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  57679. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  57680. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  57681. };
  57682. FilesInput.prototype.renderFunction = function () {
  57683. if (this._additionalRenderLoopLogicCallback) {
  57684. this._additionalRenderLoopLogicCallback();
  57685. }
  57686. if (this._currentScene) {
  57687. if (this._textureLoadingCallback) {
  57688. var remaining = this._currentScene.getWaitingItemsCount();
  57689. if (remaining > 0) {
  57690. this._textureLoadingCallback(remaining);
  57691. }
  57692. }
  57693. this._currentScene.render();
  57694. }
  57695. };
  57696. FilesInput.prototype.drag = function (e) {
  57697. e.stopPropagation();
  57698. e.preventDefault();
  57699. };
  57700. FilesInput.prototype.drop = function (eventDrop) {
  57701. eventDrop.stopPropagation();
  57702. eventDrop.preventDefault();
  57703. this.loadFiles(eventDrop);
  57704. };
  57705. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  57706. var _this = this;
  57707. var reader = folder.createReader();
  57708. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  57709. reader.readEntries(function (entries) {
  57710. remaining.count += entries.length;
  57711. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  57712. var entry = entries_1[_i];
  57713. if (entry.isFile) {
  57714. entry.file(function (file) {
  57715. file.correctName = relativePath + file.name;
  57716. files.push(file);
  57717. if (--remaining.count === 0) {
  57718. callback();
  57719. }
  57720. });
  57721. }
  57722. else if (entry.isDirectory) {
  57723. _this._traverseFolder(entry, files, remaining, callback);
  57724. }
  57725. }
  57726. if (--remaining.count) {
  57727. callback();
  57728. }
  57729. });
  57730. };
  57731. FilesInput.prototype._processFiles = function (files) {
  57732. for (var i = 0; i < files.length; i++) {
  57733. var name = files[i].correctName.toLowerCase();
  57734. var extension = name.split('.').pop();
  57735. if (!this.onProcessFileCallback(files[i], name, extension)) {
  57736. continue;
  57737. }
  57738. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  57739. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  57740. this._sceneFileToLoad = files[i];
  57741. }
  57742. else {
  57743. FilesInput.FilesToLoad[name] = files[i];
  57744. }
  57745. }
  57746. };
  57747. FilesInput.prototype.loadFiles = function (event) {
  57748. var _this = this;
  57749. if (this._startingProcessingFilesCallback)
  57750. this._startingProcessingFilesCallback();
  57751. // Handling data transfer via drag'n'drop
  57752. if (event && event.dataTransfer && event.dataTransfer.files) {
  57753. this._filesToLoad = event.dataTransfer.files;
  57754. }
  57755. // Handling files from input files
  57756. if (event && event.target && event.target.files) {
  57757. this._filesToLoad = event.target.files;
  57758. }
  57759. if (this._filesToLoad && this._filesToLoad.length > 0) {
  57760. var files_1 = new Array();
  57761. var folders = [];
  57762. var items = event.dataTransfer ? event.dataTransfer.items : null;
  57763. for (var i = 0; i < this._filesToLoad.length; i++) {
  57764. var fileToLoad = this._filesToLoad[i];
  57765. var name_1 = fileToLoad.name.toLowerCase();
  57766. var entry = void 0;
  57767. fileToLoad.correctName = name_1;
  57768. if (items) {
  57769. var item = items[i];
  57770. if (item.getAsEntry) {
  57771. entry = item.getAsEntry();
  57772. }
  57773. else if (item.webkitGetAsEntry) {
  57774. entry = item.webkitGetAsEntry();
  57775. }
  57776. }
  57777. if (!entry) {
  57778. files_1.push(fileToLoad);
  57779. }
  57780. else {
  57781. if (entry.isDirectory) {
  57782. folders.push(entry);
  57783. }
  57784. else {
  57785. files_1.push(fileToLoad);
  57786. }
  57787. }
  57788. }
  57789. if (folders.length === 0) {
  57790. this._processFiles(files_1);
  57791. this._processReload();
  57792. }
  57793. else {
  57794. var remaining = { count: folders.length };
  57795. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  57796. var folder = folders_1[_i];
  57797. this._traverseFolder(folder, files_1, remaining, function () {
  57798. _this._processFiles(files_1);
  57799. if (remaining.count === 0) {
  57800. _this._processReload();
  57801. }
  57802. });
  57803. }
  57804. }
  57805. }
  57806. };
  57807. FilesInput.prototype._processReload = function () {
  57808. if (this._onReloadCallback) {
  57809. this._onReloadCallback(this._sceneFileToLoad);
  57810. }
  57811. else {
  57812. this.reload();
  57813. }
  57814. };
  57815. FilesInput.prototype.reload = function () {
  57816. var _this = this;
  57817. // If a scene file has been provided
  57818. if (this._sceneFileToLoad) {
  57819. if (this._currentScene) {
  57820. if (BABYLON.Tools.errorsCount > 0) {
  57821. BABYLON.Tools.ClearLogCache();
  57822. }
  57823. this._engine.stopRenderLoop();
  57824. this._currentScene.dispose();
  57825. }
  57826. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  57827. _this._currentScene = newScene;
  57828. if (_this._sceneLoadedCallback) {
  57829. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  57830. }
  57831. // Wait for textures and shaders to be ready
  57832. _this._currentScene.executeWhenReady(function () {
  57833. _this._engine.runRenderLoop(function () {
  57834. _this.renderFunction();
  57835. });
  57836. });
  57837. }, function (progress) {
  57838. if (_this._progressCallback) {
  57839. _this._progressCallback(progress);
  57840. }
  57841. }, function (scene, message) {
  57842. _this._currentScene = scene;
  57843. if (_this._errorCallback) {
  57844. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, message);
  57845. }
  57846. });
  57847. }
  57848. else {
  57849. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  57850. }
  57851. };
  57852. FilesInput.FilesToLoad = {};
  57853. return FilesInput;
  57854. }());
  57855. BABYLON.FilesInput = FilesInput;
  57856. })(BABYLON || (BABYLON = {}));
  57857. //# sourceMappingURL=babylon.filesInput.js.map
  57858. var BABYLON;
  57859. (function (BABYLON) {
  57860. /**
  57861. * This class implement a typical dictionary using a string as key and the generic type T as value.
  57862. * The underlying implementation relies on an associative array to ensure the best performances.
  57863. * The value can be anything including 'null' but except 'undefined'
  57864. */
  57865. var StringDictionary = /** @class */ (function () {
  57866. function StringDictionary() {
  57867. this._count = 0;
  57868. this._data = {};
  57869. }
  57870. /**
  57871. * This will clear this dictionary and copy the content from the 'source' one.
  57872. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  57873. * @param source the dictionary to take the content from and copy to this dictionary
  57874. */
  57875. StringDictionary.prototype.copyFrom = function (source) {
  57876. var _this = this;
  57877. this.clear();
  57878. source.forEach(function (t, v) { return _this.add(t, v); });
  57879. };
  57880. /**
  57881. * Get a value based from its key
  57882. * @param key the given key to get the matching value from
  57883. * @return the value if found, otherwise undefined is returned
  57884. */
  57885. StringDictionary.prototype.get = function (key) {
  57886. var val = this._data[key];
  57887. if (val !== undefined) {
  57888. return val;
  57889. }
  57890. return undefined;
  57891. };
  57892. /**
  57893. * Get a value from its key or add it if it doesn't exist.
  57894. * This method will ensure you that a given key/data will be present in the dictionary.
  57895. * @param key the given key to get the matching value from
  57896. * @param factory the factory that will create the value if the key is not present in the dictionary.
  57897. * The factory will only be invoked if there's no data for the given key.
  57898. * @return the value corresponding to the key.
  57899. */
  57900. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  57901. var val = this.get(key);
  57902. if (val !== undefined) {
  57903. return val;
  57904. }
  57905. val = factory(key);
  57906. if (val) {
  57907. this.add(key, val);
  57908. }
  57909. return val;
  57910. };
  57911. /**
  57912. * Get a value from its key if present in the dictionary otherwise add it
  57913. * @param key the key to get the value from
  57914. * @param val if there's no such key/value pair in the dictionary add it with this value
  57915. * @return the value corresponding to the key
  57916. */
  57917. StringDictionary.prototype.getOrAdd = function (key, val) {
  57918. var curVal = this.get(key);
  57919. if (curVal !== undefined) {
  57920. return curVal;
  57921. }
  57922. this.add(key, val);
  57923. return val;
  57924. };
  57925. /**
  57926. * Check if there's a given key in the dictionary
  57927. * @param key the key to check for
  57928. * @return true if the key is present, false otherwise
  57929. */
  57930. StringDictionary.prototype.contains = function (key) {
  57931. return this._data[key] !== undefined;
  57932. };
  57933. /**
  57934. * Add a new key and its corresponding value
  57935. * @param key the key to add
  57936. * @param value the value corresponding to the key
  57937. * @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
  57938. */
  57939. StringDictionary.prototype.add = function (key, value) {
  57940. if (this._data[key] !== undefined) {
  57941. return false;
  57942. }
  57943. this._data[key] = value;
  57944. ++this._count;
  57945. return true;
  57946. };
  57947. StringDictionary.prototype.set = function (key, value) {
  57948. if (this._data[key] === undefined) {
  57949. return false;
  57950. }
  57951. this._data[key] = value;
  57952. return true;
  57953. };
  57954. /**
  57955. * Get the element of the given key and remove it from the dictionary
  57956. * @param key
  57957. */
  57958. StringDictionary.prototype.getAndRemove = function (key) {
  57959. var val = this.get(key);
  57960. if (val !== undefined) {
  57961. delete this._data[key];
  57962. --this._count;
  57963. return val;
  57964. }
  57965. return null;
  57966. };
  57967. /**
  57968. * Remove a key/value from the dictionary.
  57969. * @param key the key to remove
  57970. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  57971. */
  57972. StringDictionary.prototype.remove = function (key) {
  57973. if (this.contains(key)) {
  57974. delete this._data[key];
  57975. --this._count;
  57976. return true;
  57977. }
  57978. return false;
  57979. };
  57980. /**
  57981. * Clear the whole content of the dictionary
  57982. */
  57983. StringDictionary.prototype.clear = function () {
  57984. this._data = {};
  57985. this._count = 0;
  57986. };
  57987. Object.defineProperty(StringDictionary.prototype, "count", {
  57988. get: function () {
  57989. return this._count;
  57990. },
  57991. enumerable: true,
  57992. configurable: true
  57993. });
  57994. /**
  57995. * Execute a callback on each key/val of the dictionary.
  57996. * Note that you can remove any element in this dictionary in the callback implementation
  57997. * @param callback the callback to execute on a given key/value pair
  57998. */
  57999. StringDictionary.prototype.forEach = function (callback) {
  58000. for (var cur in this._data) {
  58001. var val = this._data[cur];
  58002. callback(cur, val);
  58003. }
  58004. };
  58005. /**
  58006. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  58007. * If the callback returns null or undefined the method will iterate to the next key/value pair
  58008. * Note that you can remove any element in this dictionary in the callback implementation
  58009. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  58010. */
  58011. StringDictionary.prototype.first = function (callback) {
  58012. for (var cur in this._data) {
  58013. var val = this._data[cur];
  58014. var res = callback(cur, val);
  58015. if (res) {
  58016. return res;
  58017. }
  58018. }
  58019. return null;
  58020. };
  58021. return StringDictionary;
  58022. }());
  58023. BABYLON.StringDictionary = StringDictionary;
  58024. })(BABYLON || (BABYLON = {}));
  58025. //# sourceMappingURL=babylon.stringDictionary.js.map
  58026. var BABYLON;
  58027. (function (BABYLON) {
  58028. var Tags = /** @class */ (function () {
  58029. function Tags() {
  58030. }
  58031. Tags.EnableFor = function (obj) {
  58032. obj._tags = obj._tags || {};
  58033. obj.hasTags = function () {
  58034. return Tags.HasTags(obj);
  58035. };
  58036. obj.addTags = function (tagsString) {
  58037. return Tags.AddTagsTo(obj, tagsString);
  58038. };
  58039. obj.removeTags = function (tagsString) {
  58040. return Tags.RemoveTagsFrom(obj, tagsString);
  58041. };
  58042. obj.matchesTagsQuery = function (tagsQuery) {
  58043. return Tags.MatchesQuery(obj, tagsQuery);
  58044. };
  58045. };
  58046. Tags.DisableFor = function (obj) {
  58047. delete obj._tags;
  58048. delete obj.hasTags;
  58049. delete obj.addTags;
  58050. delete obj.removeTags;
  58051. delete obj.matchesTagsQuery;
  58052. };
  58053. Tags.HasTags = function (obj) {
  58054. if (!obj._tags) {
  58055. return false;
  58056. }
  58057. return !BABYLON.Tools.IsEmpty(obj._tags);
  58058. };
  58059. Tags.GetTags = function (obj, asString) {
  58060. if (asString === void 0) { asString = true; }
  58061. if (!obj._tags) {
  58062. return null;
  58063. }
  58064. if (asString) {
  58065. var tagsArray = [];
  58066. for (var tag in obj._tags) {
  58067. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  58068. tagsArray.push(tag);
  58069. }
  58070. }
  58071. return tagsArray.join(" ");
  58072. }
  58073. else {
  58074. return obj._tags;
  58075. }
  58076. };
  58077. // the tags 'true' and 'false' are reserved and cannot be used as tags
  58078. // a tag cannot start with '||', '&&', and '!'
  58079. // it cannot contain whitespaces
  58080. Tags.AddTagsTo = function (obj, tagsString) {
  58081. if (!tagsString) {
  58082. return;
  58083. }
  58084. if (typeof tagsString !== "string") {
  58085. return;
  58086. }
  58087. var tags = tagsString.split(" ");
  58088. tags.forEach(function (tag, index, array) {
  58089. Tags._AddTagTo(obj, tag);
  58090. });
  58091. };
  58092. Tags._AddTagTo = function (obj, tag) {
  58093. tag = tag.trim();
  58094. if (tag === "" || tag === "true" || tag === "false") {
  58095. return;
  58096. }
  58097. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  58098. return;
  58099. }
  58100. Tags.EnableFor(obj);
  58101. obj._tags[tag] = true;
  58102. };
  58103. Tags.RemoveTagsFrom = function (obj, tagsString) {
  58104. if (!Tags.HasTags(obj)) {
  58105. return;
  58106. }
  58107. var tags = tagsString.split(" ");
  58108. for (var t in tags) {
  58109. Tags._RemoveTagFrom(obj, tags[t]);
  58110. }
  58111. };
  58112. Tags._RemoveTagFrom = function (obj, tag) {
  58113. delete obj._tags[tag];
  58114. };
  58115. Tags.MatchesQuery = function (obj, tagsQuery) {
  58116. if (tagsQuery === undefined) {
  58117. return true;
  58118. }
  58119. if (tagsQuery === "") {
  58120. return Tags.HasTags(obj);
  58121. }
  58122. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  58123. };
  58124. return Tags;
  58125. }());
  58126. BABYLON.Tags = Tags;
  58127. })(BABYLON || (BABYLON = {}));
  58128. //# sourceMappingURL=babylon.tags.js.map
  58129. var BABYLON;
  58130. (function (BABYLON) {
  58131. var AndOrNotEvaluator = /** @class */ (function () {
  58132. function AndOrNotEvaluator() {
  58133. }
  58134. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  58135. if (!query.match(/\([^\(\)]*\)/g)) {
  58136. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  58137. }
  58138. else {
  58139. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  58140. // remove parenthesis
  58141. r = r.slice(1, r.length - 1);
  58142. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  58143. });
  58144. }
  58145. if (query === "true") {
  58146. return true;
  58147. }
  58148. if (query === "false") {
  58149. return false;
  58150. }
  58151. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  58152. };
  58153. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  58154. evaluateCallback = evaluateCallback || (function (r) {
  58155. return r === "true" ? true : false;
  58156. });
  58157. var result;
  58158. var or = parenthesisContent.split("||");
  58159. for (var i in or) {
  58160. if (or.hasOwnProperty(i)) {
  58161. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  58162. var and = ori.split("&&");
  58163. if (and.length > 1) {
  58164. for (var j = 0; j < and.length; ++j) {
  58165. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  58166. if (andj !== "true" && andj !== "false") {
  58167. if (andj[0] === "!") {
  58168. result = !evaluateCallback(andj.substring(1));
  58169. }
  58170. else {
  58171. result = evaluateCallback(andj);
  58172. }
  58173. }
  58174. else {
  58175. result = andj === "true" ? true : false;
  58176. }
  58177. if (!result) {
  58178. ori = "false";
  58179. break;
  58180. }
  58181. }
  58182. }
  58183. if (result || ori === "true") {
  58184. result = true;
  58185. break;
  58186. }
  58187. // result equals false (or undefined)
  58188. if (ori !== "true" && ori !== "false") {
  58189. if (ori[0] === "!") {
  58190. result = !evaluateCallback(ori.substring(1));
  58191. }
  58192. else {
  58193. result = evaluateCallback(ori);
  58194. }
  58195. }
  58196. else {
  58197. result = ori === "true" ? true : false;
  58198. }
  58199. }
  58200. }
  58201. // the whole parenthesis scope is replaced by 'true' or 'false'
  58202. return result ? "true" : "false";
  58203. };
  58204. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  58205. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  58206. // remove whitespaces
  58207. r = r.replace(/[\s]/g, function () { return ""; });
  58208. return r.length % 2 ? "!" : "";
  58209. });
  58210. booleanString = booleanString.trim();
  58211. if (booleanString === "!true") {
  58212. booleanString = "false";
  58213. }
  58214. else if (booleanString === "!false") {
  58215. booleanString = "true";
  58216. }
  58217. return booleanString;
  58218. };
  58219. return AndOrNotEvaluator;
  58220. }());
  58221. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  58222. })(BABYLON || (BABYLON = {}));
  58223. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  58224. var BABYLON;
  58225. (function (BABYLON) {
  58226. var Database = /** @class */ (function () {
  58227. function Database(urlToScene, callbackManifestChecked) {
  58228. // Handling various flavors of prefixed version of IndexedDB
  58229. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  58230. this.callbackManifestChecked = callbackManifestChecked;
  58231. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  58232. this.db = null;
  58233. this._enableSceneOffline = false;
  58234. this._enableTexturesOffline = false;
  58235. this.manifestVersionFound = 0;
  58236. this.mustUpdateRessources = false;
  58237. this.hasReachedQuota = false;
  58238. if (!Database.IDBStorageEnabled) {
  58239. this.callbackManifestChecked(true);
  58240. }
  58241. else {
  58242. this.checkManifestFile();
  58243. }
  58244. }
  58245. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  58246. get: function () {
  58247. return this._enableSceneOffline;
  58248. },
  58249. enumerable: true,
  58250. configurable: true
  58251. });
  58252. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  58253. get: function () {
  58254. return this._enableTexturesOffline;
  58255. },
  58256. enumerable: true,
  58257. configurable: true
  58258. });
  58259. Database.prototype.checkManifestFile = function () {
  58260. var _this = this;
  58261. var noManifestFile = function () {
  58262. _this._enableSceneOffline = false;
  58263. _this._enableTexturesOffline = false;
  58264. _this.callbackManifestChecked(false);
  58265. };
  58266. var timeStampUsed = false;
  58267. var manifestURL = this.currentSceneUrl + ".manifest";
  58268. var xhr = new XMLHttpRequest();
  58269. if (navigator.onLine) {
  58270. // Adding a timestamp to by-pass browsers' cache
  58271. timeStampUsed = true;
  58272. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  58273. }
  58274. xhr.open("GET", manifestURL, true);
  58275. xhr.addEventListener("load", function () {
  58276. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  58277. try {
  58278. var manifestFile = JSON.parse(xhr.response);
  58279. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  58280. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  58281. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  58282. _this.manifestVersionFound = manifestFile.version;
  58283. }
  58284. if (_this.callbackManifestChecked) {
  58285. _this.callbackManifestChecked(true);
  58286. }
  58287. }
  58288. catch (ex) {
  58289. noManifestFile();
  58290. }
  58291. }
  58292. else {
  58293. noManifestFile();
  58294. }
  58295. }, false);
  58296. xhr.addEventListener("error", function (event) {
  58297. if (timeStampUsed) {
  58298. timeStampUsed = false;
  58299. // Let's retry without the timeStamp
  58300. // It could fail when coupled with HTML5 Offline API
  58301. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  58302. xhr.open("GET", retryManifestURL, true);
  58303. xhr.send();
  58304. }
  58305. else {
  58306. noManifestFile();
  58307. }
  58308. }, false);
  58309. try {
  58310. xhr.send();
  58311. }
  58312. catch (ex) {
  58313. BABYLON.Tools.Error("Error on XHR send request.");
  58314. this.callbackManifestChecked(false);
  58315. }
  58316. };
  58317. Database.prototype.openAsync = function (successCallback, errorCallback) {
  58318. var _this = this;
  58319. var handleError = function () {
  58320. _this.isSupported = false;
  58321. if (errorCallback)
  58322. errorCallback();
  58323. };
  58324. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  58325. // Your browser doesn't support IndexedDB
  58326. this.isSupported = false;
  58327. if (errorCallback)
  58328. errorCallback();
  58329. }
  58330. else {
  58331. // If the DB hasn't been opened or created yet
  58332. if (!this.db) {
  58333. this.hasReachedQuota = false;
  58334. this.isSupported = true;
  58335. var request = this.idbFactory.open("babylonjs", 1);
  58336. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  58337. request.onerror = function (event) {
  58338. handleError();
  58339. };
  58340. // executes when a version change transaction cannot complete due to other active transactions
  58341. request.onblocked = function (event) {
  58342. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  58343. handleError();
  58344. };
  58345. // DB has been opened successfully
  58346. request.onsuccess = function (event) {
  58347. _this.db = request.result;
  58348. successCallback();
  58349. };
  58350. // Initialization of the DB. Creating Scenes & Textures stores
  58351. request.onupgradeneeded = function (event) {
  58352. _this.db = (event.target).result;
  58353. if (_this.db) {
  58354. try {
  58355. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  58356. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  58357. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  58358. }
  58359. catch (ex) {
  58360. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  58361. handleError();
  58362. }
  58363. }
  58364. };
  58365. }
  58366. else {
  58367. if (successCallback)
  58368. successCallback();
  58369. }
  58370. }
  58371. };
  58372. Database.prototype.loadImageFromDB = function (url, image) {
  58373. var _this = this;
  58374. var completeURL = Database.ReturnFullUrlLocation(url);
  58375. var saveAndLoadImage = function () {
  58376. if (!_this.hasReachedQuota && _this.db !== null) {
  58377. // the texture is not yet in the DB, let's try to save it
  58378. _this._saveImageIntoDBAsync(completeURL, image);
  58379. }
  58380. else {
  58381. image.src = url;
  58382. }
  58383. };
  58384. if (!this.mustUpdateRessources) {
  58385. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  58386. }
  58387. else {
  58388. saveAndLoadImage();
  58389. }
  58390. };
  58391. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  58392. if (this.isSupported && this.db !== null) {
  58393. var texture;
  58394. var transaction = this.db.transaction(["textures"]);
  58395. transaction.onabort = function (event) {
  58396. image.src = url;
  58397. };
  58398. transaction.oncomplete = function (event) {
  58399. var blobTextureURL;
  58400. if (texture) {
  58401. var URL = window.URL || window.webkitURL;
  58402. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  58403. image.onerror = function () {
  58404. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  58405. image.src = url;
  58406. };
  58407. image.src = blobTextureURL;
  58408. }
  58409. else {
  58410. notInDBCallback();
  58411. }
  58412. };
  58413. var getRequest = transaction.objectStore("textures").get(url);
  58414. getRequest.onsuccess = function (event) {
  58415. texture = (event.target).result;
  58416. };
  58417. getRequest.onerror = function (event) {
  58418. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  58419. image.src = url;
  58420. };
  58421. }
  58422. else {
  58423. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  58424. image.src = url;
  58425. }
  58426. };
  58427. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  58428. var _this = this;
  58429. if (this.isSupported) {
  58430. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  58431. var generateBlobUrl = function () {
  58432. var blobTextureURL;
  58433. if (blob) {
  58434. var URL = window.URL || window.webkitURL;
  58435. try {
  58436. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  58437. }
  58438. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  58439. catch (ex) {
  58440. blobTextureURL = URL.createObjectURL(blob);
  58441. }
  58442. }
  58443. if (blobTextureURL) {
  58444. image.src = blobTextureURL;
  58445. }
  58446. };
  58447. if (Database.IsUASupportingBlobStorage) {
  58448. var xhr = new XMLHttpRequest(), blob;
  58449. xhr.open("GET", url, true);
  58450. xhr.responseType = "blob";
  58451. xhr.addEventListener("load", function () {
  58452. if (xhr.status === 200 && _this.db) {
  58453. // Blob as response (XHR2)
  58454. blob = xhr.response;
  58455. var transaction = _this.db.transaction(["textures"], "readwrite");
  58456. // the transaction could abort because of a QuotaExceededError error
  58457. transaction.onabort = function (event) {
  58458. try {
  58459. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  58460. var srcElement = (event.srcElement || event.target);
  58461. var error = srcElement.error;
  58462. if (error && error.name === "QuotaExceededError") {
  58463. _this.hasReachedQuota = true;
  58464. }
  58465. }
  58466. catch (ex) { }
  58467. generateBlobUrl();
  58468. };
  58469. transaction.oncomplete = function (event) {
  58470. generateBlobUrl();
  58471. };
  58472. var newTexture = { textureUrl: url, data: blob };
  58473. try {
  58474. // Put the blob into the dabase
  58475. var addRequest = transaction.objectStore("textures").put(newTexture);
  58476. addRequest.onsuccess = function (event) {
  58477. };
  58478. addRequest.onerror = function (event) {
  58479. generateBlobUrl();
  58480. };
  58481. }
  58482. catch (ex) {
  58483. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  58484. if (ex.code === 25) {
  58485. Database.IsUASupportingBlobStorage = false;
  58486. }
  58487. image.src = url;
  58488. }
  58489. }
  58490. else {
  58491. image.src = url;
  58492. }
  58493. }, false);
  58494. xhr.addEventListener("error", function (event) {
  58495. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  58496. image.src = url;
  58497. }, false);
  58498. xhr.send();
  58499. }
  58500. else {
  58501. image.src = url;
  58502. }
  58503. }
  58504. else {
  58505. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  58506. image.src = url;
  58507. }
  58508. };
  58509. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  58510. var _this = this;
  58511. var updateVersion = function () {
  58512. // the version is not yet in the DB or we need to update it
  58513. _this._saveVersionIntoDBAsync(url, versionLoaded);
  58514. };
  58515. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  58516. };
  58517. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  58518. var _this = this;
  58519. if (this.isSupported && this.db) {
  58520. var version;
  58521. try {
  58522. var transaction = this.db.transaction(["versions"]);
  58523. transaction.oncomplete = function (event) {
  58524. if (version) {
  58525. // If the version in the JSON file is > than the version in DB
  58526. if (_this.manifestVersionFound > version.data) {
  58527. _this.mustUpdateRessources = true;
  58528. updateInDBCallback();
  58529. }
  58530. else {
  58531. callback(version.data);
  58532. }
  58533. }
  58534. else {
  58535. _this.mustUpdateRessources = true;
  58536. updateInDBCallback();
  58537. }
  58538. };
  58539. transaction.onabort = function (event) {
  58540. callback(-1);
  58541. };
  58542. var getRequest = transaction.objectStore("versions").get(url);
  58543. getRequest.onsuccess = function (event) {
  58544. version = (event.target).result;
  58545. };
  58546. getRequest.onerror = function (event) {
  58547. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  58548. callback(-1);
  58549. };
  58550. }
  58551. catch (ex) {
  58552. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  58553. callback(-1);
  58554. }
  58555. }
  58556. else {
  58557. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  58558. callback(-1);
  58559. }
  58560. };
  58561. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  58562. var _this = this;
  58563. if (this.isSupported && !this.hasReachedQuota && this.db) {
  58564. try {
  58565. // Open a transaction to the database
  58566. var transaction = this.db.transaction(["versions"], "readwrite");
  58567. // the transaction could abort because of a QuotaExceededError error
  58568. transaction.onabort = function (event) {
  58569. try {
  58570. var error = event.srcElement['error'];
  58571. if (error && error.name === "QuotaExceededError") {
  58572. _this.hasReachedQuota = true;
  58573. }
  58574. }
  58575. catch (ex) { }
  58576. callback(-1);
  58577. };
  58578. transaction.oncomplete = function (event) {
  58579. callback(_this.manifestVersionFound);
  58580. };
  58581. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  58582. // Put the scene into the database
  58583. var addRequest = transaction.objectStore("versions").put(newVersion);
  58584. addRequest.onsuccess = function (event) {
  58585. };
  58586. addRequest.onerror = function (event) {
  58587. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  58588. };
  58589. }
  58590. catch (ex) {
  58591. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  58592. callback(-1);
  58593. }
  58594. }
  58595. else {
  58596. callback(-1);
  58597. }
  58598. };
  58599. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  58600. var _this = this;
  58601. var completeUrl = Database.ReturnFullUrlLocation(url);
  58602. var saveAndLoadFile = function () {
  58603. // the scene is not yet in the DB, let's try to save it
  58604. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  58605. };
  58606. this._checkVersionFromDB(completeUrl, function (version) {
  58607. if (version !== -1) {
  58608. if (!_this.mustUpdateRessources) {
  58609. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  58610. }
  58611. else {
  58612. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  58613. }
  58614. }
  58615. else {
  58616. if (errorCallback) {
  58617. errorCallback();
  58618. }
  58619. }
  58620. });
  58621. };
  58622. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  58623. if (this.isSupported && this.db) {
  58624. var targetStore;
  58625. if (url.indexOf(".babylon") !== -1) {
  58626. targetStore = "scenes";
  58627. }
  58628. else {
  58629. targetStore = "textures";
  58630. }
  58631. var file;
  58632. var transaction = this.db.transaction([targetStore]);
  58633. transaction.oncomplete = function (event) {
  58634. if (file) {
  58635. callback(file.data);
  58636. }
  58637. else {
  58638. notInDBCallback();
  58639. }
  58640. };
  58641. transaction.onabort = function (event) {
  58642. notInDBCallback();
  58643. };
  58644. var getRequest = transaction.objectStore(targetStore).get(url);
  58645. getRequest.onsuccess = function (event) {
  58646. file = (event.target).result;
  58647. };
  58648. getRequest.onerror = function (event) {
  58649. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  58650. notInDBCallback();
  58651. };
  58652. }
  58653. else {
  58654. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  58655. callback();
  58656. }
  58657. };
  58658. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  58659. var _this = this;
  58660. if (this.isSupported) {
  58661. var targetStore;
  58662. if (url.indexOf(".babylon") !== -1) {
  58663. targetStore = "scenes";
  58664. }
  58665. else {
  58666. targetStore = "textures";
  58667. }
  58668. // Create XHR
  58669. var xhr = new XMLHttpRequest();
  58670. var fileData;
  58671. xhr.open("GET", url, true);
  58672. if (useArrayBuffer) {
  58673. xhr.responseType = "arraybuffer";
  58674. }
  58675. if (progressCallback) {
  58676. xhr.onprogress = progressCallback;
  58677. }
  58678. xhr.addEventListener("load", function () {
  58679. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  58680. // Blob as response (XHR2)
  58681. //fileData = xhr.responseText;
  58682. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  58683. if (!_this.hasReachedQuota && _this.db) {
  58684. // Open a transaction to the database
  58685. var transaction = _this.db.transaction([targetStore], "readwrite");
  58686. // the transaction could abort because of a QuotaExceededError error
  58687. transaction.onabort = function (event) {
  58688. try {
  58689. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  58690. var error = event.srcElement['error'];
  58691. if (error && error.name === "QuotaExceededError") {
  58692. _this.hasReachedQuota = true;
  58693. }
  58694. }
  58695. catch (ex) { }
  58696. callback(fileData);
  58697. };
  58698. transaction.oncomplete = function (event) {
  58699. callback(fileData);
  58700. };
  58701. var newFile;
  58702. if (targetStore === "scenes") {
  58703. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  58704. }
  58705. else {
  58706. newFile = { textureUrl: url, data: fileData };
  58707. }
  58708. try {
  58709. // Put the scene into the database
  58710. var addRequest = transaction.objectStore(targetStore).put(newFile);
  58711. addRequest.onsuccess = function (event) {
  58712. };
  58713. addRequest.onerror = function (event) {
  58714. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  58715. };
  58716. }
  58717. catch (ex) {
  58718. callback(fileData);
  58719. }
  58720. }
  58721. else {
  58722. callback(fileData);
  58723. }
  58724. }
  58725. else {
  58726. callback();
  58727. }
  58728. }, false);
  58729. xhr.addEventListener("error", function (event) {
  58730. BABYLON.Tools.Error("error on XHR request.");
  58731. callback();
  58732. }, false);
  58733. xhr.send();
  58734. }
  58735. else {
  58736. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  58737. callback();
  58738. }
  58739. };
  58740. Database.IsUASupportingBlobStorage = true;
  58741. Database.IDBStorageEnabled = true;
  58742. Database.parseURL = function (url) {
  58743. var a = document.createElement('a');
  58744. a.href = url;
  58745. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  58746. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  58747. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  58748. return absLocation;
  58749. };
  58750. Database.ReturnFullUrlLocation = function (url) {
  58751. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  58752. return (Database.parseURL(window.location.href) + url);
  58753. }
  58754. else {
  58755. return url;
  58756. }
  58757. };
  58758. return Database;
  58759. }());
  58760. BABYLON.Database = Database;
  58761. })(BABYLON || (BABYLON = {}));
  58762. //# sourceMappingURL=babylon.database.js.map
  58763. var BABYLON;
  58764. (function (BABYLON) {
  58765. var FresnelParameters = /** @class */ (function () {
  58766. function FresnelParameters() {
  58767. this._isEnabled = true;
  58768. this.leftColor = BABYLON.Color3.White();
  58769. this.rightColor = BABYLON.Color3.Black();
  58770. this.bias = 0;
  58771. this.power = 1;
  58772. }
  58773. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  58774. get: function () {
  58775. return this._isEnabled;
  58776. },
  58777. set: function (value) {
  58778. if (this._isEnabled === value) {
  58779. return;
  58780. }
  58781. this._isEnabled = value;
  58782. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  58783. },
  58784. enumerable: true,
  58785. configurable: true
  58786. });
  58787. FresnelParameters.prototype.clone = function () {
  58788. var newFresnelParameters = new FresnelParameters();
  58789. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  58790. return newFresnelParameters;
  58791. };
  58792. FresnelParameters.prototype.serialize = function () {
  58793. var serializationObject = {};
  58794. serializationObject.isEnabled = this.isEnabled;
  58795. serializationObject.leftColor = this.leftColor;
  58796. serializationObject.rightColor = this.rightColor;
  58797. serializationObject.bias = this.bias;
  58798. serializationObject.power = this.power;
  58799. return serializationObject;
  58800. };
  58801. FresnelParameters.Parse = function (parsedFresnelParameters) {
  58802. var fresnelParameters = new FresnelParameters();
  58803. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  58804. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  58805. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  58806. fresnelParameters.bias = parsedFresnelParameters.bias;
  58807. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  58808. return fresnelParameters;
  58809. };
  58810. return FresnelParameters;
  58811. }());
  58812. BABYLON.FresnelParameters = FresnelParameters;
  58813. })(BABYLON || (BABYLON = {}));
  58814. //# sourceMappingURL=babylon.fresnelParameters.js.map
  58815. var BABYLON;
  58816. (function (BABYLON) {
  58817. var MultiMaterial = /** @class */ (function (_super) {
  58818. __extends(MultiMaterial, _super);
  58819. function MultiMaterial(name, scene) {
  58820. var _this = _super.call(this, name, scene, true) || this;
  58821. scene.multiMaterials.push(_this);
  58822. _this.subMaterials = new Array();
  58823. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  58824. return _this;
  58825. }
  58826. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  58827. get: function () {
  58828. return this._subMaterials;
  58829. },
  58830. set: function (value) {
  58831. this._subMaterials = value;
  58832. this._hookArray(value);
  58833. },
  58834. enumerable: true,
  58835. configurable: true
  58836. });
  58837. MultiMaterial.prototype._hookArray = function (array) {
  58838. var _this = this;
  58839. var oldPush = array.push;
  58840. array.push = function () {
  58841. var items = [];
  58842. for (var _i = 0; _i < arguments.length; _i++) {
  58843. items[_i] = arguments[_i];
  58844. }
  58845. var result = oldPush.apply(array, items);
  58846. _this._markAllSubMeshesAsTexturesDirty();
  58847. return result;
  58848. };
  58849. var oldSplice = array.splice;
  58850. array.splice = function (index, deleteCount) {
  58851. var deleted = oldSplice.apply(array, [index, deleteCount]);
  58852. _this._markAllSubMeshesAsTexturesDirty();
  58853. return deleted;
  58854. };
  58855. };
  58856. // Properties
  58857. MultiMaterial.prototype.getSubMaterial = function (index) {
  58858. if (index < 0 || index >= this.subMaterials.length) {
  58859. return this.getScene().defaultMaterial;
  58860. }
  58861. return this.subMaterials[index];
  58862. };
  58863. MultiMaterial.prototype.getActiveTextures = function () {
  58864. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  58865. if (subMaterial) {
  58866. return subMaterial.getActiveTextures();
  58867. }
  58868. else {
  58869. return [];
  58870. }
  58871. }));
  58872. var _a;
  58873. };
  58874. // Methods
  58875. MultiMaterial.prototype.getClassName = function () {
  58876. return "MultiMaterial";
  58877. };
  58878. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  58879. for (var index = 0; index < this.subMaterials.length; index++) {
  58880. var subMaterial = this.subMaterials[index];
  58881. if (subMaterial) {
  58882. if (subMaterial.storeEffectOnSubMeshes) {
  58883. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  58884. return false;
  58885. }
  58886. continue;
  58887. }
  58888. if (!subMaterial.isReady(mesh)) {
  58889. return false;
  58890. }
  58891. }
  58892. }
  58893. return true;
  58894. };
  58895. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  58896. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  58897. for (var index = 0; index < this.subMaterials.length; index++) {
  58898. var subMaterial = null;
  58899. var current = this.subMaterials[index];
  58900. if (cloneChildren && current) {
  58901. subMaterial = current.clone(name + "-" + current.name);
  58902. }
  58903. else {
  58904. subMaterial = this.subMaterials[index];
  58905. }
  58906. newMultiMaterial.subMaterials.push(subMaterial);
  58907. }
  58908. return newMultiMaterial;
  58909. };
  58910. MultiMaterial.prototype.serialize = function () {
  58911. var serializationObject = {};
  58912. serializationObject.name = this.name;
  58913. serializationObject.id = this.id;
  58914. if (BABYLON.Tags) {
  58915. serializationObject.tags = BABYLON.Tags.GetTags(this);
  58916. }
  58917. serializationObject.materials = [];
  58918. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  58919. var subMat = this.subMaterials[matIndex];
  58920. if (subMat) {
  58921. serializationObject.materials.push(subMat.id);
  58922. }
  58923. else {
  58924. serializationObject.materials.push(null);
  58925. }
  58926. }
  58927. return serializationObject;
  58928. };
  58929. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  58930. var scene = this.getScene();
  58931. if (!scene) {
  58932. return;
  58933. }
  58934. var index = scene.multiMaterials.indexOf(this);
  58935. if (index >= 0) {
  58936. scene.multiMaterials.splice(index, 1);
  58937. }
  58938. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  58939. };
  58940. return MultiMaterial;
  58941. }(BABYLON.Material));
  58942. BABYLON.MultiMaterial = MultiMaterial;
  58943. })(BABYLON || (BABYLON = {}));
  58944. //# sourceMappingURL=babylon.multiMaterial.js.map
  58945. var BABYLON;
  58946. (function (BABYLON) {
  58947. var FreeCameraTouchInput = /** @class */ (function () {
  58948. function FreeCameraTouchInput() {
  58949. this._offsetX = null;
  58950. this._offsetY = null;
  58951. this._pointerPressed = new Array();
  58952. this.touchAngularSensibility = 200000.0;
  58953. this.touchMoveSensibility = 250.0;
  58954. }
  58955. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  58956. var _this = this;
  58957. var previousPosition = null;
  58958. if (this._pointerInput === undefined) {
  58959. this._onLostFocus = function (evt) {
  58960. _this._offsetX = null;
  58961. _this._offsetY = null;
  58962. };
  58963. this._pointerInput = function (p, s) {
  58964. var evt = p.event;
  58965. if (evt.pointerType === "mouse") {
  58966. return;
  58967. }
  58968. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  58969. if (!noPreventDefault) {
  58970. evt.preventDefault();
  58971. }
  58972. _this._pointerPressed.push(evt.pointerId);
  58973. if (_this._pointerPressed.length !== 1) {
  58974. return;
  58975. }
  58976. previousPosition = {
  58977. x: evt.clientX,
  58978. y: evt.clientY
  58979. };
  58980. }
  58981. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  58982. if (!noPreventDefault) {
  58983. evt.preventDefault();
  58984. }
  58985. var index = _this._pointerPressed.indexOf(evt.pointerId);
  58986. if (index === -1) {
  58987. return;
  58988. }
  58989. _this._pointerPressed.splice(index, 1);
  58990. if (index != 0) {
  58991. return;
  58992. }
  58993. previousPosition = null;
  58994. _this._offsetX = null;
  58995. _this._offsetY = null;
  58996. }
  58997. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  58998. if (!noPreventDefault) {
  58999. evt.preventDefault();
  59000. }
  59001. if (!previousPosition) {
  59002. return;
  59003. }
  59004. var index = _this._pointerPressed.indexOf(evt.pointerId);
  59005. if (index != 0) {
  59006. return;
  59007. }
  59008. _this._offsetX = evt.clientX - previousPosition.x;
  59009. _this._offsetY = -(evt.clientY - previousPosition.y);
  59010. }
  59011. };
  59012. }
  59013. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  59014. if (this._onLostFocus) {
  59015. element.addEventListener("blur", this._onLostFocus);
  59016. }
  59017. };
  59018. FreeCameraTouchInput.prototype.detachControl = function (element) {
  59019. if (this._pointerInput && element) {
  59020. if (this._observer) {
  59021. this.camera.getScene().onPointerObservable.remove(this._observer);
  59022. this._observer = null;
  59023. }
  59024. if (this._onLostFocus) {
  59025. element.removeEventListener("blur", this._onLostFocus);
  59026. this._onLostFocus = null;
  59027. }
  59028. this._pointerPressed = [];
  59029. this._offsetX = null;
  59030. this._offsetY = null;
  59031. }
  59032. };
  59033. FreeCameraTouchInput.prototype.checkInputs = function () {
  59034. if (this._offsetX && this._offsetY) {
  59035. var camera = this.camera;
  59036. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  59037. if (this._pointerPressed.length > 1) {
  59038. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  59039. }
  59040. else {
  59041. var speed = camera._computeLocalCameraSpeed();
  59042. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  59043. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  59044. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  59045. }
  59046. }
  59047. };
  59048. FreeCameraTouchInput.prototype.getClassName = function () {
  59049. return "FreeCameraTouchInput";
  59050. };
  59051. FreeCameraTouchInput.prototype.getSimpleName = function () {
  59052. return "touch";
  59053. };
  59054. __decorate([
  59055. BABYLON.serialize()
  59056. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  59057. __decorate([
  59058. BABYLON.serialize()
  59059. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  59060. return FreeCameraTouchInput;
  59061. }());
  59062. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  59063. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  59064. })(BABYLON || (BABYLON = {}));
  59065. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  59066. var BABYLON;
  59067. (function (BABYLON) {
  59068. // We're mainly based on the logic defined into the FreeCamera code
  59069. var TouchCamera = /** @class */ (function (_super) {
  59070. __extends(TouchCamera, _super);
  59071. //-- end properties for backward compatibility for inputs
  59072. function TouchCamera(name, position, scene) {
  59073. var _this = _super.call(this, name, position, scene) || this;
  59074. _this.inputs.addTouch();
  59075. _this._setupInputs();
  59076. return _this;
  59077. }
  59078. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  59079. //-- Begin properties for backward compatibility for inputs
  59080. get: function () {
  59081. var touch = this.inputs.attached["touch"];
  59082. if (touch)
  59083. return touch.touchAngularSensibility;
  59084. return 0;
  59085. },
  59086. set: function (value) {
  59087. var touch = this.inputs.attached["touch"];
  59088. if (touch)
  59089. touch.touchAngularSensibility = value;
  59090. },
  59091. enumerable: true,
  59092. configurable: true
  59093. });
  59094. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  59095. get: function () {
  59096. var touch = this.inputs.attached["touch"];
  59097. if (touch)
  59098. return touch.touchMoveSensibility;
  59099. return 0;
  59100. },
  59101. set: function (value) {
  59102. var touch = this.inputs.attached["touch"];
  59103. if (touch)
  59104. touch.touchMoveSensibility = value;
  59105. },
  59106. enumerable: true,
  59107. configurable: true
  59108. });
  59109. TouchCamera.prototype.getClassName = function () {
  59110. return "TouchCamera";
  59111. };
  59112. TouchCamera.prototype._setupInputs = function () {
  59113. var mouse = this.inputs.attached["mouse"];
  59114. if (mouse) {
  59115. mouse.touchEnabled = false;
  59116. }
  59117. };
  59118. return TouchCamera;
  59119. }(BABYLON.FreeCamera));
  59120. BABYLON.TouchCamera = TouchCamera;
  59121. })(BABYLON || (BABYLON = {}));
  59122. //# sourceMappingURL=babylon.touchCamera.js.map
  59123. var BABYLON;
  59124. (function (BABYLON) {
  59125. var ProceduralTexture = /** @class */ (function (_super) {
  59126. __extends(ProceduralTexture, _super);
  59127. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  59128. if (fallbackTexture === void 0) { fallbackTexture = null; }
  59129. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59130. if (isCube === void 0) { isCube = false; }
  59131. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  59132. _this.isCube = isCube;
  59133. _this.isEnabled = true;
  59134. _this._currentRefreshId = -1;
  59135. _this._refreshRate = 1;
  59136. _this._vertexBuffers = {};
  59137. _this._uniforms = new Array();
  59138. _this._samplers = new Array();
  59139. _this._textures = {};
  59140. _this._floats = {};
  59141. _this._floatsArrays = {};
  59142. _this._colors3 = {};
  59143. _this._colors4 = {};
  59144. _this._vectors2 = {};
  59145. _this._vectors3 = {};
  59146. _this._matrices = {};
  59147. _this._fallbackTextureUsed = false;
  59148. scene._proceduralTextures.push(_this);
  59149. _this._engine = scene.getEngine();
  59150. _this.name = name;
  59151. _this.isRenderTarget = true;
  59152. _this._size = size;
  59153. _this._generateMipMaps = generateMipMaps;
  59154. _this.setFragment(fragment);
  59155. _this._fallbackTexture = fallbackTexture;
  59156. if (isCube) {
  59157. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  59158. _this.setFloat("face", 0);
  59159. }
  59160. else {
  59161. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  59162. }
  59163. // VBO
  59164. var vertices = [];
  59165. vertices.push(1, 1);
  59166. vertices.push(-1, 1);
  59167. vertices.push(-1, -1);
  59168. vertices.push(1, -1);
  59169. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  59170. _this._createIndexBuffer();
  59171. return _this;
  59172. }
  59173. ProceduralTexture.prototype._createIndexBuffer = function () {
  59174. var engine = this._engine;
  59175. // Indices
  59176. var indices = [];
  59177. indices.push(0);
  59178. indices.push(1);
  59179. indices.push(2);
  59180. indices.push(0);
  59181. indices.push(2);
  59182. indices.push(3);
  59183. this._indexBuffer = engine.createIndexBuffer(indices);
  59184. };
  59185. ProceduralTexture.prototype._rebuild = function () {
  59186. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  59187. if (vb) {
  59188. vb._rebuild();
  59189. }
  59190. this._createIndexBuffer();
  59191. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  59192. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  59193. }
  59194. };
  59195. ProceduralTexture.prototype.reset = function () {
  59196. if (this._effect === undefined) {
  59197. return;
  59198. }
  59199. var engine = this._engine;
  59200. engine._releaseEffect(this._effect);
  59201. };
  59202. ProceduralTexture.prototype.isReady = function () {
  59203. var _this = this;
  59204. var engine = this._engine;
  59205. var shaders;
  59206. if (!this._fragment) {
  59207. return false;
  59208. }
  59209. if (this._fallbackTextureUsed) {
  59210. return true;
  59211. }
  59212. if (this._fragment.fragmentElement !== undefined) {
  59213. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  59214. }
  59215. else {
  59216. shaders = { vertex: "procedural", fragment: this._fragment };
  59217. }
  59218. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  59219. _this.releaseInternalTexture();
  59220. if (_this._fallbackTexture) {
  59221. _this._texture = _this._fallbackTexture._texture;
  59222. if (_this._texture) {
  59223. _this._texture.incrementReferences();
  59224. }
  59225. }
  59226. _this._fallbackTextureUsed = true;
  59227. });
  59228. return this._effect.isReady();
  59229. };
  59230. ProceduralTexture.prototype.resetRefreshCounter = function () {
  59231. this._currentRefreshId = -1;
  59232. };
  59233. ProceduralTexture.prototype.setFragment = function (fragment) {
  59234. this._fragment = fragment;
  59235. };
  59236. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  59237. get: function () {
  59238. return this._refreshRate;
  59239. },
  59240. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  59241. set: function (value) {
  59242. this._refreshRate = value;
  59243. this.resetRefreshCounter();
  59244. },
  59245. enumerable: true,
  59246. configurable: true
  59247. });
  59248. ProceduralTexture.prototype._shouldRender = function () {
  59249. if (!this.isEnabled || !this.isReady() || !this._texture) {
  59250. return false;
  59251. }
  59252. if (this._fallbackTextureUsed) {
  59253. return false;
  59254. }
  59255. if (this._currentRefreshId === -1) {
  59256. this._currentRefreshId = 1;
  59257. return true;
  59258. }
  59259. if (this.refreshRate === this._currentRefreshId) {
  59260. this._currentRefreshId = 1;
  59261. return true;
  59262. }
  59263. this._currentRefreshId++;
  59264. return false;
  59265. };
  59266. ProceduralTexture.prototype.getRenderSize = function () {
  59267. return this._size;
  59268. };
  59269. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  59270. if (this._fallbackTextureUsed) {
  59271. return;
  59272. }
  59273. this.releaseInternalTexture();
  59274. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  59275. };
  59276. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  59277. if (this._uniforms.indexOf(uniformName) === -1) {
  59278. this._uniforms.push(uniformName);
  59279. }
  59280. };
  59281. ProceduralTexture.prototype.setTexture = function (name, texture) {
  59282. if (this._samplers.indexOf(name) === -1) {
  59283. this._samplers.push(name);
  59284. }
  59285. this._textures[name] = texture;
  59286. return this;
  59287. };
  59288. ProceduralTexture.prototype.setFloat = function (name, value) {
  59289. this._checkUniform(name);
  59290. this._floats[name] = value;
  59291. return this;
  59292. };
  59293. ProceduralTexture.prototype.setFloats = function (name, value) {
  59294. this._checkUniform(name);
  59295. this._floatsArrays[name] = value;
  59296. return this;
  59297. };
  59298. ProceduralTexture.prototype.setColor3 = function (name, value) {
  59299. this._checkUniform(name);
  59300. this._colors3[name] = value;
  59301. return this;
  59302. };
  59303. ProceduralTexture.prototype.setColor4 = function (name, value) {
  59304. this._checkUniform(name);
  59305. this._colors4[name] = value;
  59306. return this;
  59307. };
  59308. ProceduralTexture.prototype.setVector2 = function (name, value) {
  59309. this._checkUniform(name);
  59310. this._vectors2[name] = value;
  59311. return this;
  59312. };
  59313. ProceduralTexture.prototype.setVector3 = function (name, value) {
  59314. this._checkUniform(name);
  59315. this._vectors3[name] = value;
  59316. return this;
  59317. };
  59318. ProceduralTexture.prototype.setMatrix = function (name, value) {
  59319. this._checkUniform(name);
  59320. this._matrices[name] = value;
  59321. return this;
  59322. };
  59323. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  59324. var scene = this.getScene();
  59325. if (!scene) {
  59326. return;
  59327. }
  59328. var engine = this._engine;
  59329. // Render
  59330. engine.enableEffect(this._effect);
  59331. engine.setState(false);
  59332. // Texture
  59333. for (var name in this._textures) {
  59334. this._effect.setTexture(name, this._textures[name]);
  59335. }
  59336. // Float
  59337. for (name in this._floats) {
  59338. this._effect.setFloat(name, this._floats[name]);
  59339. }
  59340. // Floats
  59341. for (name in this._floatsArrays) {
  59342. this._effect.setArray(name, this._floatsArrays[name]);
  59343. }
  59344. // Color3
  59345. for (name in this._colors3) {
  59346. this._effect.setColor3(name, this._colors3[name]);
  59347. }
  59348. // Color4
  59349. for (name in this._colors4) {
  59350. var color = this._colors4[name];
  59351. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  59352. }
  59353. // Vector2
  59354. for (name in this._vectors2) {
  59355. this._effect.setVector2(name, this._vectors2[name]);
  59356. }
  59357. // Vector3
  59358. for (name in this._vectors3) {
  59359. this._effect.setVector3(name, this._vectors3[name]);
  59360. }
  59361. // Matrix
  59362. for (name in this._matrices) {
  59363. this._effect.setMatrix(name, this._matrices[name]);
  59364. }
  59365. if (!this._texture) {
  59366. return;
  59367. }
  59368. if (this.isCube) {
  59369. for (var face = 0; face < 6; face++) {
  59370. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  59371. // VBOs
  59372. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  59373. this._effect.setFloat("face", face);
  59374. // Clear
  59375. engine.clear(scene.clearColor, true, true, true);
  59376. // Draw order
  59377. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  59378. // Mipmaps
  59379. if (face === 5) {
  59380. engine.generateMipMapsForCubemap(this._texture);
  59381. }
  59382. }
  59383. }
  59384. else {
  59385. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  59386. // VBOs
  59387. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  59388. // Clear
  59389. engine.clear(scene.clearColor, true, true, true);
  59390. // Draw order
  59391. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  59392. }
  59393. // Unbind
  59394. engine.unBindFramebuffer(this._texture, this.isCube);
  59395. if (this.onGenerated) {
  59396. this.onGenerated();
  59397. }
  59398. };
  59399. ProceduralTexture.prototype.clone = function () {
  59400. var textureSize = this.getSize();
  59401. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  59402. // Base texture
  59403. newTexture.hasAlpha = this.hasAlpha;
  59404. newTexture.level = this.level;
  59405. // RenderTarget Texture
  59406. newTexture.coordinatesMode = this.coordinatesMode;
  59407. return newTexture;
  59408. };
  59409. ProceduralTexture.prototype.dispose = function () {
  59410. var scene = this.getScene();
  59411. if (!scene) {
  59412. return;
  59413. }
  59414. var index = scene._proceduralTextures.indexOf(this);
  59415. if (index >= 0) {
  59416. scene._proceduralTextures.splice(index, 1);
  59417. }
  59418. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  59419. if (vertexBuffer) {
  59420. vertexBuffer.dispose();
  59421. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  59422. }
  59423. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  59424. this._indexBuffer = null;
  59425. }
  59426. _super.prototype.dispose.call(this);
  59427. };
  59428. return ProceduralTexture;
  59429. }(BABYLON.Texture));
  59430. BABYLON.ProceduralTexture = ProceduralTexture;
  59431. })(BABYLON || (BABYLON = {}));
  59432. //# sourceMappingURL=babylon.proceduralTexture.js.map
  59433. var BABYLON;
  59434. (function (BABYLON) {
  59435. var CustomProceduralTexture = /** @class */ (function (_super) {
  59436. __extends(CustomProceduralTexture, _super);
  59437. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  59438. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  59439. _this._animate = true;
  59440. _this._time = 0;
  59441. _this._texturePath = texturePath;
  59442. //Try to load json
  59443. _this.loadJson(texturePath);
  59444. _this.refreshRate = 1;
  59445. return _this;
  59446. }
  59447. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  59448. var _this = this;
  59449. var noConfigFile = function () {
  59450. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  59451. try {
  59452. _this.setFragment(_this._texturePath);
  59453. }
  59454. catch (ex) {
  59455. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  59456. }
  59457. };
  59458. var configFileUrl = jsonUrl + "/config.json";
  59459. var xhr = new XMLHttpRequest();
  59460. xhr.open("GET", configFileUrl, true);
  59461. xhr.addEventListener("load", function () {
  59462. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  59463. try {
  59464. _this._config = JSON.parse(xhr.response);
  59465. _this.updateShaderUniforms();
  59466. _this.updateTextures();
  59467. _this.setFragment(_this._texturePath + "/custom");
  59468. _this._animate = _this._config.animate;
  59469. _this.refreshRate = _this._config.refreshrate;
  59470. }
  59471. catch (ex) {
  59472. noConfigFile();
  59473. }
  59474. }
  59475. else {
  59476. noConfigFile();
  59477. }
  59478. }, false);
  59479. xhr.addEventListener("error", function () {
  59480. noConfigFile();
  59481. }, false);
  59482. try {
  59483. xhr.send();
  59484. }
  59485. catch (ex) {
  59486. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  59487. }
  59488. };
  59489. CustomProceduralTexture.prototype.isReady = function () {
  59490. if (!_super.prototype.isReady.call(this)) {
  59491. return false;
  59492. }
  59493. for (var name in this._textures) {
  59494. var texture = this._textures[name];
  59495. if (!texture.isReady()) {
  59496. return false;
  59497. }
  59498. }
  59499. return true;
  59500. };
  59501. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  59502. var scene = this.getScene();
  59503. if (this._animate && scene) {
  59504. this._time += scene.getAnimationRatio() * 0.03;
  59505. this.updateShaderUniforms();
  59506. }
  59507. _super.prototype.render.call(this, useCameraPostProcess);
  59508. };
  59509. CustomProceduralTexture.prototype.updateTextures = function () {
  59510. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  59511. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  59512. }
  59513. };
  59514. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  59515. if (this._config) {
  59516. for (var j = 0; j < this._config.uniforms.length; j++) {
  59517. var uniform = this._config.uniforms[j];
  59518. switch (uniform.type) {
  59519. case "float":
  59520. this.setFloat(uniform.name, uniform.value);
  59521. break;
  59522. case "color3":
  59523. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  59524. break;
  59525. case "color4":
  59526. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  59527. break;
  59528. case "vector2":
  59529. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  59530. break;
  59531. case "vector3":
  59532. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  59533. break;
  59534. }
  59535. }
  59536. }
  59537. this.setFloat("time", this._time);
  59538. };
  59539. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  59540. get: function () {
  59541. return this._animate;
  59542. },
  59543. set: function (value) {
  59544. this._animate = value;
  59545. },
  59546. enumerable: true,
  59547. configurable: true
  59548. });
  59549. return CustomProceduralTexture;
  59550. }(BABYLON.ProceduralTexture));
  59551. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  59552. })(BABYLON || (BABYLON = {}));
  59553. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  59554. var BABYLON;
  59555. (function (BABYLON) {
  59556. var FreeCameraGamepadInput = /** @class */ (function () {
  59557. function FreeCameraGamepadInput() {
  59558. this.gamepadAngularSensibility = 200;
  59559. this.gamepadMoveSensibility = 40;
  59560. // private members
  59561. this._cameraTransform = BABYLON.Matrix.Identity();
  59562. this._deltaTransform = BABYLON.Vector3.Zero();
  59563. this._vector3 = BABYLON.Vector3.Zero();
  59564. this._vector2 = BABYLON.Vector2.Zero();
  59565. }
  59566. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  59567. var _this = this;
  59568. var manager = this.camera.getScene().gamepadManager;
  59569. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  59570. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  59571. // prioritize XBOX gamepads.
  59572. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  59573. _this.gamepad = gamepad;
  59574. }
  59575. }
  59576. });
  59577. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  59578. if (_this.gamepad === gamepad) {
  59579. _this.gamepad = null;
  59580. }
  59581. });
  59582. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  59583. };
  59584. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  59585. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  59586. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  59587. this.gamepad = null;
  59588. };
  59589. FreeCameraGamepadInput.prototype.checkInputs = function () {
  59590. if (this.gamepad && this.gamepad.leftStick) {
  59591. var camera = this.camera;
  59592. var LSValues = this.gamepad.leftStick;
  59593. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  59594. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  59595. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  59596. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  59597. var RSValues = this.gamepad.rightStick;
  59598. if (RSValues) {
  59599. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  59600. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  59601. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  59602. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  59603. }
  59604. else {
  59605. RSValues = { x: 0, y: 0 };
  59606. }
  59607. if (!camera.rotationQuaternion) {
  59608. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  59609. }
  59610. else {
  59611. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  59612. }
  59613. var speed = camera._computeLocalCameraSpeed() * 50.0;
  59614. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  59615. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  59616. camera.cameraDirection.addInPlace(this._deltaTransform);
  59617. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  59618. camera.cameraRotation.addInPlace(this._vector2);
  59619. }
  59620. };
  59621. FreeCameraGamepadInput.prototype.getClassName = function () {
  59622. return "FreeCameraGamepadInput";
  59623. };
  59624. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  59625. return "gamepad";
  59626. };
  59627. __decorate([
  59628. BABYLON.serialize()
  59629. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  59630. __decorate([
  59631. BABYLON.serialize()
  59632. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  59633. return FreeCameraGamepadInput;
  59634. }());
  59635. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  59636. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  59637. })(BABYLON || (BABYLON = {}));
  59638. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  59639. var BABYLON;
  59640. (function (BABYLON) {
  59641. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  59642. function ArcRotateCameraGamepadInput() {
  59643. this.gamepadRotationSensibility = 80;
  59644. this.gamepadMoveSensibility = 40;
  59645. }
  59646. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  59647. var _this = this;
  59648. var manager = this.camera.getScene().gamepadManager;
  59649. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  59650. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  59651. // prioritize XBOX gamepads.
  59652. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  59653. _this.gamepad = gamepad;
  59654. }
  59655. }
  59656. });
  59657. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  59658. if (_this.gamepad === gamepad) {
  59659. _this.gamepad = null;
  59660. }
  59661. });
  59662. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  59663. };
  59664. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  59665. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  59666. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  59667. this.gamepad = null;
  59668. };
  59669. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  59670. if (this.gamepad) {
  59671. var camera = this.camera;
  59672. var RSValues = this.gamepad.rightStick;
  59673. if (RSValues) {
  59674. if (RSValues.x != 0) {
  59675. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  59676. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  59677. camera.inertialAlphaOffset += normalizedRX;
  59678. }
  59679. }
  59680. if (RSValues.y != 0) {
  59681. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  59682. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  59683. camera.inertialBetaOffset += normalizedRY;
  59684. }
  59685. }
  59686. }
  59687. var LSValues = this.gamepad.leftStick;
  59688. if (LSValues && LSValues.y != 0) {
  59689. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  59690. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  59691. this.camera.inertialRadiusOffset -= normalizedLY;
  59692. }
  59693. }
  59694. }
  59695. };
  59696. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  59697. return "ArcRotateCameraGamepadInput";
  59698. };
  59699. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  59700. return "gamepad";
  59701. };
  59702. __decorate([
  59703. BABYLON.serialize()
  59704. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  59705. __decorate([
  59706. BABYLON.serialize()
  59707. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  59708. return ArcRotateCameraGamepadInput;
  59709. }());
  59710. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  59711. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  59712. })(BABYLON || (BABYLON = {}));
  59713. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  59714. var BABYLON;
  59715. (function (BABYLON) {
  59716. var GamepadManager = /** @class */ (function () {
  59717. function GamepadManager(_scene) {
  59718. var _this = this;
  59719. this._scene = _scene;
  59720. this._babylonGamepads = [];
  59721. this._oneGamepadConnected = false;
  59722. this._isMonitoring = false;
  59723. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  59724. if (!BABYLON.Tools.IsWindowObjectExist()) {
  59725. this._gamepadEventSupported = false;
  59726. }
  59727. else {
  59728. this._gamepadEventSupported = 'GamepadEvent' in window;
  59729. this._gamepadSupport = (navigator.getGamepads ||
  59730. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  59731. }
  59732. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  59733. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  59734. for (var i in _this._babylonGamepads) {
  59735. var gamepad = _this._babylonGamepads[i];
  59736. if (gamepad && gamepad._isConnected) {
  59737. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  59738. }
  59739. }
  59740. });
  59741. this._onGamepadConnectedEvent = function (evt) {
  59742. var gamepad = evt.gamepad;
  59743. if (gamepad.index in _this._babylonGamepads) {
  59744. if (_this._babylonGamepads[gamepad.index].isConnected) {
  59745. return;
  59746. }
  59747. }
  59748. var newGamepad;
  59749. if (_this._babylonGamepads[gamepad.index]) {
  59750. newGamepad = _this._babylonGamepads[gamepad.index];
  59751. newGamepad.browserGamepad = gamepad;
  59752. newGamepad._isConnected = true;
  59753. }
  59754. else {
  59755. newGamepad = _this._addNewGamepad(gamepad);
  59756. }
  59757. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  59758. _this._startMonitoringGamepads();
  59759. };
  59760. this._onGamepadDisconnectedEvent = function (evt) {
  59761. var gamepad = evt.gamepad;
  59762. // Remove the gamepad from the list of gamepads to monitor.
  59763. for (var i in _this._babylonGamepads) {
  59764. if (_this._babylonGamepads[i].index === gamepad.index) {
  59765. var disconnectedGamepad = _this._babylonGamepads[i];
  59766. disconnectedGamepad._isConnected = false;
  59767. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  59768. break;
  59769. }
  59770. }
  59771. };
  59772. if (this._gamepadSupport) {
  59773. //first add already-connected gamepads
  59774. this._updateGamepadObjects();
  59775. if (this._babylonGamepads.length) {
  59776. this._startMonitoringGamepads();
  59777. }
  59778. // Checking if the gamepad connected event is supported (like in Firefox)
  59779. if (this._gamepadEventSupported) {
  59780. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  59781. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  59782. }
  59783. else {
  59784. this._startMonitoringGamepads();
  59785. }
  59786. }
  59787. }
  59788. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  59789. get: function () {
  59790. return this._babylonGamepads;
  59791. },
  59792. enumerable: true,
  59793. configurable: true
  59794. });
  59795. GamepadManager.prototype.getGamepadByType = function (type) {
  59796. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  59797. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  59798. var gamepad = _a[_i];
  59799. if (gamepad && gamepad.type === type) {
  59800. return gamepad;
  59801. }
  59802. }
  59803. return null;
  59804. };
  59805. GamepadManager.prototype.dispose = function () {
  59806. if (this._gamepadEventSupported) {
  59807. if (this._onGamepadConnectedEvent) {
  59808. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  59809. }
  59810. if (this._onGamepadDisconnectedEvent) {
  59811. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  59812. }
  59813. this._onGamepadConnectedEvent = null;
  59814. this._onGamepadDisconnectedEvent = null;
  59815. }
  59816. this._babylonGamepads.forEach(function (gamepad) {
  59817. gamepad.dispose();
  59818. });
  59819. this.onGamepadConnectedObservable.clear();
  59820. this.onGamepadDisconnectedObservable.clear();
  59821. this._oneGamepadConnected = false;
  59822. this._stopMonitoringGamepads();
  59823. this._babylonGamepads = [];
  59824. };
  59825. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  59826. if (!this._oneGamepadConnected) {
  59827. this._oneGamepadConnected = true;
  59828. }
  59829. var newGamepad;
  59830. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  59831. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  59832. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  59833. }
  59834. else if (gamepad.pose) {
  59835. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  59836. }
  59837. else {
  59838. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  59839. }
  59840. this._babylonGamepads[newGamepad.index] = newGamepad;
  59841. return newGamepad;
  59842. };
  59843. GamepadManager.prototype._startMonitoringGamepads = function () {
  59844. if (!this._isMonitoring) {
  59845. this._isMonitoring = true;
  59846. //back-comp
  59847. if (!this._scene) {
  59848. this._checkGamepadsStatus();
  59849. }
  59850. }
  59851. };
  59852. GamepadManager.prototype._stopMonitoringGamepads = function () {
  59853. this._isMonitoring = false;
  59854. };
  59855. GamepadManager.prototype._checkGamepadsStatus = function () {
  59856. var _this = this;
  59857. // Hack to be compatible Chrome
  59858. this._updateGamepadObjects();
  59859. for (var i in this._babylonGamepads) {
  59860. var gamepad = this._babylonGamepads[i];
  59861. if (!gamepad || !gamepad.isConnected) {
  59862. continue;
  59863. }
  59864. gamepad.update();
  59865. }
  59866. if (this._isMonitoring && !this._scene) {
  59867. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  59868. }
  59869. };
  59870. // This function is called only on Chrome, which does not properly support
  59871. // connection/disconnection events and forces you to recopy again the gamepad object
  59872. GamepadManager.prototype._updateGamepadObjects = function () {
  59873. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  59874. for (var i = 0; i < gamepads.length; i++) {
  59875. if (gamepads[i]) {
  59876. if (!this._babylonGamepads[gamepads[i].index]) {
  59877. var newGamepad = this._addNewGamepad(gamepads[i]);
  59878. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  59879. }
  59880. else {
  59881. // Forced to copy again this object for Chrome for unknown reason
  59882. this._babylonGamepads[i].browserGamepad = gamepads[i];
  59883. if (!this._babylonGamepads[i].isConnected) {
  59884. this._babylonGamepads[i]._isConnected = true;
  59885. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  59886. }
  59887. }
  59888. }
  59889. }
  59890. };
  59891. return GamepadManager;
  59892. }());
  59893. BABYLON.GamepadManager = GamepadManager;
  59894. })(BABYLON || (BABYLON = {}));
  59895. //# sourceMappingURL=babylon.gamepadManager.js.map
  59896. var BABYLON;
  59897. (function (BABYLON) {
  59898. var StickValues = /** @class */ (function () {
  59899. function StickValues(x, y) {
  59900. this.x = x;
  59901. this.y = y;
  59902. }
  59903. return StickValues;
  59904. }());
  59905. BABYLON.StickValues = StickValues;
  59906. var Gamepad = /** @class */ (function () {
  59907. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  59908. if (leftStickX === void 0) { leftStickX = 0; }
  59909. if (leftStickY === void 0) { leftStickY = 1; }
  59910. if (rightStickX === void 0) { rightStickX = 2; }
  59911. if (rightStickY === void 0) { rightStickY = 3; }
  59912. this.id = id;
  59913. this.index = index;
  59914. this.browserGamepad = browserGamepad;
  59915. this._isConnected = true;
  59916. this._invertLeftStickY = false;
  59917. this.type = Gamepad.GAMEPAD;
  59918. this._leftStickAxisX = leftStickX;
  59919. this._leftStickAxisY = leftStickY;
  59920. this._rightStickAxisX = rightStickX;
  59921. this._rightStickAxisY = rightStickY;
  59922. if (this.browserGamepad.axes.length >= 2) {
  59923. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  59924. }
  59925. if (this.browserGamepad.axes.length >= 4) {
  59926. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  59927. }
  59928. }
  59929. Object.defineProperty(Gamepad.prototype, "isConnected", {
  59930. get: function () {
  59931. return this._isConnected;
  59932. },
  59933. enumerable: true,
  59934. configurable: true
  59935. });
  59936. Gamepad.prototype.onleftstickchanged = function (callback) {
  59937. this._onleftstickchanged = callback;
  59938. };
  59939. Gamepad.prototype.onrightstickchanged = function (callback) {
  59940. this._onrightstickchanged = callback;
  59941. };
  59942. Object.defineProperty(Gamepad.prototype, "leftStick", {
  59943. get: function () {
  59944. return this._leftStick;
  59945. },
  59946. set: function (newValues) {
  59947. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  59948. this._onleftstickchanged(newValues);
  59949. }
  59950. this._leftStick = newValues;
  59951. },
  59952. enumerable: true,
  59953. configurable: true
  59954. });
  59955. Object.defineProperty(Gamepad.prototype, "rightStick", {
  59956. get: function () {
  59957. return this._rightStick;
  59958. },
  59959. set: function (newValues) {
  59960. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  59961. this._onrightstickchanged(newValues);
  59962. }
  59963. this._rightStick = newValues;
  59964. },
  59965. enumerable: true,
  59966. configurable: true
  59967. });
  59968. Gamepad.prototype.update = function () {
  59969. if (this._leftStick) {
  59970. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  59971. if (this._invertLeftStickY) {
  59972. this.leftStick.y *= -1;
  59973. }
  59974. }
  59975. if (this._rightStick) {
  59976. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  59977. }
  59978. };
  59979. Gamepad.prototype.dispose = function () {
  59980. };
  59981. Gamepad.GAMEPAD = 0;
  59982. Gamepad.GENERIC = 1;
  59983. Gamepad.XBOX = 2;
  59984. Gamepad.POSE_ENABLED = 3;
  59985. return Gamepad;
  59986. }());
  59987. BABYLON.Gamepad = Gamepad;
  59988. var GenericPad = /** @class */ (function (_super) {
  59989. __extends(GenericPad, _super);
  59990. function GenericPad(id, index, browserGamepad) {
  59991. var _this = _super.call(this, id, index, browserGamepad) || this;
  59992. _this.onButtonDownObservable = new BABYLON.Observable();
  59993. _this.onButtonUpObservable = new BABYLON.Observable();
  59994. _this.type = Gamepad.GENERIC;
  59995. _this._buttons = new Array(browserGamepad.buttons.length);
  59996. return _this;
  59997. }
  59998. GenericPad.prototype.onbuttondown = function (callback) {
  59999. this._onbuttondown = callback;
  60000. };
  60001. GenericPad.prototype.onbuttonup = function (callback) {
  60002. this._onbuttonup = callback;
  60003. };
  60004. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  60005. if (newValue !== currentValue) {
  60006. if (newValue === 1) {
  60007. if (this._onbuttondown) {
  60008. this._onbuttondown(buttonIndex);
  60009. }
  60010. this.onButtonDownObservable.notifyObservers(buttonIndex);
  60011. }
  60012. if (newValue === 0) {
  60013. if (this._onbuttonup) {
  60014. this._onbuttonup(buttonIndex);
  60015. }
  60016. this.onButtonUpObservable.notifyObservers(buttonIndex);
  60017. }
  60018. }
  60019. return newValue;
  60020. };
  60021. GenericPad.prototype.update = function () {
  60022. _super.prototype.update.call(this);
  60023. for (var index = 0; index < this._buttons.length; index++) {
  60024. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  60025. }
  60026. };
  60027. GenericPad.prototype.dispose = function () {
  60028. _super.prototype.dispose.call(this);
  60029. this.onButtonDownObservable.clear();
  60030. this.onButtonUpObservable.clear();
  60031. };
  60032. return GenericPad;
  60033. }(Gamepad));
  60034. BABYLON.GenericPad = GenericPad;
  60035. })(BABYLON || (BABYLON = {}));
  60036. //# sourceMappingURL=babylon.gamepad.js.map
  60037. var BABYLON;
  60038. (function (BABYLON) {
  60039. var Xbox360Button;
  60040. (function (Xbox360Button) {
  60041. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  60042. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  60043. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  60044. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  60045. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  60046. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  60047. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  60048. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  60049. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  60050. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  60051. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  60052. var Xbox360Dpad;
  60053. (function (Xbox360Dpad) {
  60054. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  60055. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  60056. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  60057. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  60058. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  60059. var Xbox360Pad = /** @class */ (function (_super) {
  60060. __extends(Xbox360Pad, _super);
  60061. function Xbox360Pad(id, index, gamepad, xboxOne) {
  60062. if (xboxOne === void 0) { xboxOne = false; }
  60063. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  60064. _this._leftTrigger = 0;
  60065. _this._rightTrigger = 0;
  60066. _this.onButtonDownObservable = new BABYLON.Observable();
  60067. _this.onButtonUpObservable = new BABYLON.Observable();
  60068. _this.onPadDownObservable = new BABYLON.Observable();
  60069. _this.onPadUpObservable = new BABYLON.Observable();
  60070. _this._buttonA = 0;
  60071. _this._buttonB = 0;
  60072. _this._buttonX = 0;
  60073. _this._buttonY = 0;
  60074. _this._buttonBack = 0;
  60075. _this._buttonStart = 0;
  60076. _this._buttonLB = 0;
  60077. _this._buttonRB = 0;
  60078. _this._buttonLeftStick = 0;
  60079. _this._buttonRightStick = 0;
  60080. _this._dPadUp = 0;
  60081. _this._dPadDown = 0;
  60082. _this._dPadLeft = 0;
  60083. _this._dPadRight = 0;
  60084. _this._isXboxOnePad = false;
  60085. _this.type = BABYLON.Gamepad.XBOX;
  60086. _this._isXboxOnePad = xboxOne;
  60087. return _this;
  60088. }
  60089. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  60090. this._onlefttriggerchanged = callback;
  60091. };
  60092. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  60093. this._onrighttriggerchanged = callback;
  60094. };
  60095. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  60096. get: function () {
  60097. return this._leftTrigger;
  60098. },
  60099. set: function (newValue) {
  60100. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  60101. this._onlefttriggerchanged(newValue);
  60102. }
  60103. this._leftTrigger = newValue;
  60104. },
  60105. enumerable: true,
  60106. configurable: true
  60107. });
  60108. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  60109. get: function () {
  60110. return this._rightTrigger;
  60111. },
  60112. set: function (newValue) {
  60113. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  60114. this._onrighttriggerchanged(newValue);
  60115. }
  60116. this._rightTrigger = newValue;
  60117. },
  60118. enumerable: true,
  60119. configurable: true
  60120. });
  60121. Xbox360Pad.prototype.onbuttondown = function (callback) {
  60122. this._onbuttondown = callback;
  60123. };
  60124. Xbox360Pad.prototype.onbuttonup = function (callback) {
  60125. this._onbuttonup = callback;
  60126. };
  60127. Xbox360Pad.prototype.ondpaddown = function (callback) {
  60128. this._ondpaddown = callback;
  60129. };
  60130. Xbox360Pad.prototype.ondpadup = function (callback) {
  60131. this._ondpadup = callback;
  60132. };
  60133. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  60134. if (newValue !== currentValue) {
  60135. if (newValue === 1) {
  60136. if (this._onbuttondown) {
  60137. this._onbuttondown(buttonType);
  60138. }
  60139. this.onButtonDownObservable.notifyObservers(buttonType);
  60140. }
  60141. if (newValue === 0) {
  60142. if (this._onbuttonup) {
  60143. this._onbuttonup(buttonType);
  60144. }
  60145. this.onButtonUpObservable.notifyObservers(buttonType);
  60146. }
  60147. }
  60148. return newValue;
  60149. };
  60150. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  60151. if (newValue !== currentValue) {
  60152. if (newValue === 1) {
  60153. if (this._ondpaddown) {
  60154. this._ondpaddown(buttonType);
  60155. }
  60156. this.onPadDownObservable.notifyObservers(buttonType);
  60157. }
  60158. if (newValue === 0) {
  60159. if (this._ondpadup) {
  60160. this._ondpadup(buttonType);
  60161. }
  60162. this.onPadUpObservable.notifyObservers(buttonType);
  60163. }
  60164. }
  60165. return newValue;
  60166. };
  60167. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  60168. get: function () {
  60169. return this._buttonA;
  60170. },
  60171. set: function (value) {
  60172. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  60173. },
  60174. enumerable: true,
  60175. configurable: true
  60176. });
  60177. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  60178. get: function () {
  60179. return this._buttonB;
  60180. },
  60181. set: function (value) {
  60182. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  60183. },
  60184. enumerable: true,
  60185. configurable: true
  60186. });
  60187. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  60188. get: function () {
  60189. return this._buttonX;
  60190. },
  60191. set: function (value) {
  60192. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  60193. },
  60194. enumerable: true,
  60195. configurable: true
  60196. });
  60197. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  60198. get: function () {
  60199. return this._buttonY;
  60200. },
  60201. set: function (value) {
  60202. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  60203. },
  60204. enumerable: true,
  60205. configurable: true
  60206. });
  60207. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  60208. get: function () {
  60209. return this._buttonStart;
  60210. },
  60211. set: function (value) {
  60212. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  60213. },
  60214. enumerable: true,
  60215. configurable: true
  60216. });
  60217. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  60218. get: function () {
  60219. return this._buttonBack;
  60220. },
  60221. set: function (value) {
  60222. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  60223. },
  60224. enumerable: true,
  60225. configurable: true
  60226. });
  60227. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  60228. get: function () {
  60229. return this._buttonLB;
  60230. },
  60231. set: function (value) {
  60232. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  60233. },
  60234. enumerable: true,
  60235. configurable: true
  60236. });
  60237. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  60238. get: function () {
  60239. return this._buttonRB;
  60240. },
  60241. set: function (value) {
  60242. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  60243. },
  60244. enumerable: true,
  60245. configurable: true
  60246. });
  60247. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  60248. get: function () {
  60249. return this._buttonLeftStick;
  60250. },
  60251. set: function (value) {
  60252. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  60253. },
  60254. enumerable: true,
  60255. configurable: true
  60256. });
  60257. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  60258. get: function () {
  60259. return this._buttonRightStick;
  60260. },
  60261. set: function (value) {
  60262. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  60263. },
  60264. enumerable: true,
  60265. configurable: true
  60266. });
  60267. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  60268. get: function () {
  60269. return this._dPadUp;
  60270. },
  60271. set: function (value) {
  60272. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  60273. },
  60274. enumerable: true,
  60275. configurable: true
  60276. });
  60277. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  60278. get: function () {
  60279. return this._dPadDown;
  60280. },
  60281. set: function (value) {
  60282. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  60283. },
  60284. enumerable: true,
  60285. configurable: true
  60286. });
  60287. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  60288. get: function () {
  60289. return this._dPadLeft;
  60290. },
  60291. set: function (value) {
  60292. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  60293. },
  60294. enumerable: true,
  60295. configurable: true
  60296. });
  60297. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  60298. get: function () {
  60299. return this._dPadRight;
  60300. },
  60301. set: function (value) {
  60302. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  60303. },
  60304. enumerable: true,
  60305. configurable: true
  60306. });
  60307. Xbox360Pad.prototype.update = function () {
  60308. _super.prototype.update.call(this);
  60309. if (this._isXboxOnePad) {
  60310. this.buttonA = this.browserGamepad.buttons[0].value;
  60311. this.buttonB = this.browserGamepad.buttons[1].value;
  60312. this.buttonX = this.browserGamepad.buttons[2].value;
  60313. this.buttonY = this.browserGamepad.buttons[3].value;
  60314. this.buttonLB = this.browserGamepad.buttons[4].value;
  60315. this.buttonRB = this.browserGamepad.buttons[5].value;
  60316. this.leftTrigger = this.browserGamepad.axes[2];
  60317. this.rightTrigger = this.browserGamepad.axes[5];
  60318. this.buttonBack = this.browserGamepad.buttons[9].value;
  60319. this.buttonStart = this.browserGamepad.buttons[8].value;
  60320. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  60321. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  60322. this.dPadUp = this.browserGamepad.buttons[11].value;
  60323. this.dPadDown = this.browserGamepad.buttons[12].value;
  60324. this.dPadLeft = this.browserGamepad.buttons[13].value;
  60325. this.dPadRight = this.browserGamepad.buttons[14].value;
  60326. }
  60327. else {
  60328. this.buttonA = this.browserGamepad.buttons[0].value;
  60329. this.buttonB = this.browserGamepad.buttons[1].value;
  60330. this.buttonX = this.browserGamepad.buttons[2].value;
  60331. this.buttonY = this.browserGamepad.buttons[3].value;
  60332. this.buttonLB = this.browserGamepad.buttons[4].value;
  60333. this.buttonRB = this.browserGamepad.buttons[5].value;
  60334. this.leftTrigger = this.browserGamepad.buttons[6].value;
  60335. this.rightTrigger = this.browserGamepad.buttons[7].value;
  60336. this.buttonBack = this.browserGamepad.buttons[8].value;
  60337. this.buttonStart = this.browserGamepad.buttons[9].value;
  60338. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  60339. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  60340. this.dPadUp = this.browserGamepad.buttons[12].value;
  60341. this.dPadDown = this.browserGamepad.buttons[13].value;
  60342. this.dPadLeft = this.browserGamepad.buttons[14].value;
  60343. this.dPadRight = this.browserGamepad.buttons[15].value;
  60344. }
  60345. };
  60346. Xbox360Pad.prototype.dispose = function () {
  60347. _super.prototype.dispose.call(this);
  60348. this.onButtonDownObservable.clear();
  60349. this.onButtonUpObservable.clear();
  60350. this.onPadDownObservable.clear();
  60351. this.onPadUpObservable.clear();
  60352. };
  60353. return Xbox360Pad;
  60354. }(BABYLON.Gamepad));
  60355. BABYLON.Xbox360Pad = Xbox360Pad;
  60356. })(BABYLON || (BABYLON = {}));
  60357. //# sourceMappingURL=babylon.xboxGamepad.js.map
  60358. var BABYLON;
  60359. (function (BABYLON) {
  60360. var PoseEnabledControllerType;
  60361. (function (PoseEnabledControllerType) {
  60362. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  60363. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  60364. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  60365. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  60366. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 4] = "GENERIC";
  60367. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  60368. var PoseEnabledControllerHelper = /** @class */ (function () {
  60369. function PoseEnabledControllerHelper() {
  60370. }
  60371. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  60372. // Oculus Touch
  60373. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  60374. return new BABYLON.OculusTouchController(vrGamepad);
  60375. }
  60376. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  60377. return new BABYLON.WindowsMotionController(vrGamepad);
  60378. }
  60379. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  60380. return new BABYLON.ViveController(vrGamepad);
  60381. }
  60382. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  60383. return new BABYLON.GearVRController(vrGamepad);
  60384. }
  60385. else {
  60386. return new BABYLON.GenericController(vrGamepad);
  60387. }
  60388. };
  60389. return PoseEnabledControllerHelper;
  60390. }());
  60391. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  60392. var PoseEnabledController = /** @class */ (function (_super) {
  60393. __extends(PoseEnabledController, _super);
  60394. function PoseEnabledController(browserGamepad) {
  60395. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  60396. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  60397. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  60398. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  60399. // Represents device position and rotation in babylon space
  60400. _this.devicePosition = BABYLON.Vector3.Zero();
  60401. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  60402. _this.deviceScaleFactor = 1;
  60403. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  60404. _this._deviceToWorld = BABYLON.Matrix.Identity();
  60405. _this._workingMatrix = BABYLON.Matrix.Identity();
  60406. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  60407. _this.controllerType = PoseEnabledControllerType.GENERIC;
  60408. _this.position = BABYLON.Vector3.Zero();
  60409. _this.rotationQuaternion = new BABYLON.Quaternion();
  60410. _this._calculatedPosition = BABYLON.Vector3.Zero();
  60411. _this._calculatedRotation = new BABYLON.Quaternion();
  60412. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  60413. return _this;
  60414. }
  60415. PoseEnabledController.prototype.update = function () {
  60416. _super.prototype.update.call(this);
  60417. var pose = this.browserGamepad.pose;
  60418. this.updateFromDevice(pose);
  60419. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  60420. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  60421. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  60422. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  60423. if (this._mesh) {
  60424. this._mesh.position.copyFrom(this.devicePosition);
  60425. if (this._mesh.rotationQuaternion) {
  60426. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  60427. }
  60428. }
  60429. };
  60430. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  60431. if (poseData) {
  60432. this.rawPose = poseData;
  60433. if (poseData.position) {
  60434. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  60435. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  60436. this._deviceRoomPosition.z *= -1;
  60437. }
  60438. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  60439. this._calculatedPosition.addInPlace(this.position);
  60440. }
  60441. var pose = this.rawPose;
  60442. if (poseData.orientation && pose.orientation) {
  60443. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  60444. if (this._mesh) {
  60445. if (this._mesh.getScene().useRightHandedSystem) {
  60446. this._deviceRoomRotationQuaternion.z *= -1;
  60447. this._deviceRoomRotationQuaternion.w *= -1;
  60448. }
  60449. else {
  60450. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  60451. }
  60452. }
  60453. // if the camera is set, rotate to the camera's rotation
  60454. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  60455. }
  60456. }
  60457. };
  60458. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  60459. if (this._mesh) {
  60460. this._mesh.parent = null;
  60461. }
  60462. this._mesh = mesh;
  60463. if (this._poseControlledCamera) {
  60464. this._mesh.parent = this._poseControlledCamera;
  60465. }
  60466. if (!this._mesh.rotationQuaternion) {
  60467. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  60468. }
  60469. };
  60470. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  60471. this._poseControlledCamera = camera;
  60472. if (this._mesh) {
  60473. this._mesh.parent = this._poseControlledCamera;
  60474. }
  60475. };
  60476. PoseEnabledController.prototype.dispose = function () {
  60477. if (this._mesh) {
  60478. this._mesh.dispose();
  60479. }
  60480. this._mesh = null;
  60481. _super.prototype.dispose.call(this);
  60482. };
  60483. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  60484. get: function () {
  60485. return this._mesh;
  60486. },
  60487. enumerable: true,
  60488. configurable: true
  60489. });
  60490. PoseEnabledController.prototype.getForwardRay = function (length) {
  60491. if (length === void 0) { length = 100; }
  60492. if (!this.mesh) {
  60493. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  60494. }
  60495. var m = this.mesh.getWorldMatrix();
  60496. var origin = m.getTranslation();
  60497. var forward = new BABYLON.Vector3(0, 0, -1);
  60498. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  60499. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  60500. return new BABYLON.Ray(origin, direction, length);
  60501. };
  60502. return PoseEnabledController;
  60503. }(BABYLON.Gamepad));
  60504. BABYLON.PoseEnabledController = PoseEnabledController;
  60505. })(BABYLON || (BABYLON = {}));
  60506. //# sourceMappingURL=babylon.poseEnabledController.js.map
  60507. var BABYLON;
  60508. (function (BABYLON) {
  60509. var WebVRController = /** @class */ (function (_super) {
  60510. __extends(WebVRController, _super);
  60511. function WebVRController(vrGamepad) {
  60512. var _this = _super.call(this, vrGamepad) || this;
  60513. // Observables
  60514. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  60515. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  60516. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  60517. _this.onPadStateChangedObservable = new BABYLON.Observable();
  60518. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  60519. _this.pad = { x: 0, y: 0 };
  60520. // avoid GC, store state in a tmp object
  60521. _this._changes = {
  60522. pressChanged: false,
  60523. touchChanged: false,
  60524. valueChanged: false,
  60525. changed: false
  60526. };
  60527. _this._buttons = new Array(vrGamepad.buttons.length);
  60528. _this.hand = vrGamepad.hand;
  60529. return _this;
  60530. }
  60531. WebVRController.prototype.onButtonStateChange = function (callback) {
  60532. this._onButtonStateChange = callback;
  60533. };
  60534. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  60535. get: function () {
  60536. return this._defaultModel;
  60537. },
  60538. enumerable: true,
  60539. configurable: true
  60540. });
  60541. WebVRController.prototype.update = function () {
  60542. _super.prototype.update.call(this);
  60543. for (var index = 0; index < this._buttons.length; index++) {
  60544. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  60545. }
  60546. ;
  60547. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  60548. this.pad.x = this.leftStick.x;
  60549. this.pad.y = this.leftStick.y;
  60550. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  60551. }
  60552. };
  60553. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  60554. if (!newState) {
  60555. newState = {
  60556. pressed: false,
  60557. touched: false,
  60558. value: 0
  60559. };
  60560. }
  60561. if (!currentState) {
  60562. this._buttons[buttonIndex] = {
  60563. pressed: newState.pressed,
  60564. touched: newState.touched,
  60565. value: newState.value
  60566. };
  60567. return;
  60568. }
  60569. this._checkChanges(newState, currentState);
  60570. if (this._changes.changed) {
  60571. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  60572. this.handleButtonChange(buttonIndex, newState, this._changes);
  60573. }
  60574. this._buttons[buttonIndex].pressed = newState.pressed;
  60575. this._buttons[buttonIndex].touched = newState.touched;
  60576. // oculus triggers are never 0, thou not touched.
  60577. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  60578. };
  60579. WebVRController.prototype._checkChanges = function (newState, currentState) {
  60580. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  60581. this._changes.touchChanged = newState.touched !== currentState.touched;
  60582. this._changes.valueChanged = newState.value !== currentState.value;
  60583. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  60584. return this._changes;
  60585. };
  60586. WebVRController.prototype.dispose = function () {
  60587. _super.prototype.dispose.call(this);
  60588. this.onTriggerStateChangedObservable.clear();
  60589. this.onMainButtonStateChangedObservable.clear();
  60590. this.onSecondaryButtonStateChangedObservable.clear();
  60591. this.onPadStateChangedObservable.clear();
  60592. this.onPadValuesChangedObservable.clear();
  60593. };
  60594. return WebVRController;
  60595. }(BABYLON.PoseEnabledController));
  60596. BABYLON.WebVRController = WebVRController;
  60597. })(BABYLON || (BABYLON = {}));
  60598. //# sourceMappingURL=babylon.webVRController.js.map
  60599. var BABYLON;
  60600. (function (BABYLON) {
  60601. var OculusTouchController = /** @class */ (function (_super) {
  60602. __extends(OculusTouchController, _super);
  60603. function OculusTouchController(vrGamepad) {
  60604. var _this = _super.call(this, vrGamepad) || this;
  60605. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  60606. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  60607. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  60608. return _this;
  60609. }
  60610. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  60611. var _this = this;
  60612. var meshName;
  60613. // Hand
  60614. if (this.hand === 'left') {
  60615. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  60616. }
  60617. else {
  60618. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  60619. }
  60620. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  60621. /*
  60622. Parent Mesh name: oculus_touch_left
  60623. - body
  60624. - trigger
  60625. - thumbstick
  60626. - grip
  60627. - button_y
  60628. - button_x
  60629. - button_enter
  60630. */
  60631. _this._defaultModel = newMeshes[1];
  60632. _this.attachToMesh(_this._defaultModel);
  60633. if (meshLoaded) {
  60634. meshLoaded(_this._defaultModel);
  60635. }
  60636. });
  60637. };
  60638. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  60639. // helper getters for left and right hand.
  60640. get: function () {
  60641. if (this.hand === 'right') {
  60642. return this.onMainButtonStateChangedObservable;
  60643. }
  60644. else {
  60645. throw new Error('No A button on left hand');
  60646. }
  60647. },
  60648. enumerable: true,
  60649. configurable: true
  60650. });
  60651. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  60652. get: function () {
  60653. if (this.hand === 'right') {
  60654. return this.onSecondaryButtonStateChangedObservable;
  60655. }
  60656. else {
  60657. throw new Error('No B button on left hand');
  60658. }
  60659. },
  60660. enumerable: true,
  60661. configurable: true
  60662. });
  60663. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  60664. get: function () {
  60665. if (this.hand === 'left') {
  60666. return this.onMainButtonStateChangedObservable;
  60667. }
  60668. else {
  60669. throw new Error('No X button on right hand');
  60670. }
  60671. },
  60672. enumerable: true,
  60673. configurable: true
  60674. });
  60675. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  60676. get: function () {
  60677. if (this.hand === 'left') {
  60678. return this.onSecondaryButtonStateChangedObservable;
  60679. }
  60680. else {
  60681. throw new Error('No Y button on right hand');
  60682. }
  60683. },
  60684. enumerable: true,
  60685. configurable: true
  60686. });
  60687. /*
  60688. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  60689. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  60690. 2) secondary trigger (same)
  60691. 3) A (right) X (left), touch, pressed = value
  60692. 4) B / Y
  60693. 5) thumb rest
  60694. */
  60695. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  60696. var notifyObject = state; //{ state: state, changes: changes };
  60697. var triggerDirection = this.hand === 'right' ? -1 : 1;
  60698. switch (buttonIdx) {
  60699. case 0:
  60700. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  60701. return;
  60702. case 1:// index trigger
  60703. if (this._defaultModel) {
  60704. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  60705. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  60706. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  60707. }
  60708. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  60709. return;
  60710. case 2:// secondary trigger
  60711. if (this._defaultModel) {
  60712. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  60713. }
  60714. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  60715. return;
  60716. case 3:
  60717. if (this._defaultModel) {
  60718. if (notifyObject.pressed) {
  60719. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  60720. }
  60721. else {
  60722. (this._defaultModel.getChildren()[1]).position.y = 0;
  60723. }
  60724. }
  60725. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  60726. return;
  60727. case 4:
  60728. if (this._defaultModel) {
  60729. if (notifyObject.pressed) {
  60730. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  60731. }
  60732. else {
  60733. (this._defaultModel.getChildren()[2]).position.y = 0;
  60734. }
  60735. }
  60736. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  60737. return;
  60738. case 5:
  60739. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  60740. return;
  60741. }
  60742. };
  60743. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  60744. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  60745. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  60746. return OculusTouchController;
  60747. }(BABYLON.WebVRController));
  60748. BABYLON.OculusTouchController = OculusTouchController;
  60749. })(BABYLON || (BABYLON = {}));
  60750. //# sourceMappingURL=babylon.oculusTouchController.js.map
  60751. var BABYLON;
  60752. (function (BABYLON) {
  60753. var ViveController = /** @class */ (function (_super) {
  60754. __extends(ViveController, _super);
  60755. function ViveController(vrGamepad) {
  60756. var _this = _super.call(this, vrGamepad) || this;
  60757. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  60758. _this._invertLeftStickY = true;
  60759. return _this;
  60760. }
  60761. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  60762. var _this = this;
  60763. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  60764. /*
  60765. Parent Mesh name: ViveWand
  60766. - body
  60767. - r_gripper
  60768. - l_gripper
  60769. - menu_button
  60770. - system_button
  60771. - trackpad
  60772. - trigger
  60773. - LED
  60774. */
  60775. _this._defaultModel = newMeshes[1];
  60776. _this.attachToMesh(_this._defaultModel);
  60777. if (meshLoaded) {
  60778. meshLoaded(_this._defaultModel);
  60779. }
  60780. });
  60781. };
  60782. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  60783. get: function () {
  60784. return this.onMainButtonStateChangedObservable;
  60785. },
  60786. enumerable: true,
  60787. configurable: true
  60788. });
  60789. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  60790. get: function () {
  60791. return this.onMainButtonStateChangedObservable;
  60792. },
  60793. enumerable: true,
  60794. configurable: true
  60795. });
  60796. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  60797. get: function () {
  60798. return this.onSecondaryButtonStateChangedObservable;
  60799. },
  60800. enumerable: true,
  60801. configurable: true
  60802. });
  60803. /**
  60804. * Vive mapping:
  60805. * 0: touchpad
  60806. * 1: trigger
  60807. * 2: left AND right buttons
  60808. * 3: menu button
  60809. */
  60810. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  60811. var notifyObject = state; //{ state: state, changes: changes };
  60812. switch (buttonIdx) {
  60813. case 0:
  60814. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  60815. return;
  60816. case 1:// index trigger
  60817. if (this._defaultModel) {
  60818. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  60819. }
  60820. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  60821. return;
  60822. case 2:// left AND right button
  60823. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  60824. return;
  60825. case 3:
  60826. if (this._defaultModel) {
  60827. if (notifyObject.pressed) {
  60828. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  60829. }
  60830. else {
  60831. (this._defaultModel.getChildren()[2]).position.y = 0;
  60832. }
  60833. }
  60834. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  60835. return;
  60836. }
  60837. };
  60838. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  60839. ViveController.MODEL_FILENAME = 'wand.babylon';
  60840. return ViveController;
  60841. }(BABYLON.WebVRController));
  60842. BABYLON.ViveController = ViveController;
  60843. })(BABYLON || (BABYLON = {}));
  60844. //# sourceMappingURL=babylon.viveController.js.map
  60845. var BABYLON;
  60846. (function (BABYLON) {
  60847. var GenericController = /** @class */ (function (_super) {
  60848. __extends(GenericController, _super);
  60849. function GenericController(vrGamepad) {
  60850. return _super.call(this, vrGamepad) || this;
  60851. }
  60852. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  60853. var _this = this;
  60854. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  60855. _this._defaultModel = newMeshes[1];
  60856. _this.attachToMesh(_this._defaultModel);
  60857. if (meshLoaded) {
  60858. meshLoaded(_this._defaultModel);
  60859. }
  60860. });
  60861. };
  60862. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  60863. console.log("Button id: " + buttonIdx + "state: ");
  60864. console.dir(state);
  60865. };
  60866. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  60867. GenericController.MODEL_FILENAME = 'generic.babylon';
  60868. return GenericController;
  60869. }(BABYLON.WebVRController));
  60870. BABYLON.GenericController = GenericController;
  60871. })(BABYLON || (BABYLON = {}));
  60872. //# sourceMappingURL=babylon.genericController.js.map
  60873. var BABYLON;
  60874. (function (BABYLON) {
  60875. var LoadedMeshInfo = /** @class */ (function () {
  60876. function LoadedMeshInfo() {
  60877. this.buttonMeshes = {};
  60878. this.axisMeshes = {};
  60879. }
  60880. return LoadedMeshInfo;
  60881. }());
  60882. var WindowsMotionController = /** @class */ (function (_super) {
  60883. __extends(WindowsMotionController, _super);
  60884. function WindowsMotionController(vrGamepad) {
  60885. var _this = _super.call(this, vrGamepad) || this;
  60886. _this._mapping = {
  60887. // Semantic button names
  60888. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  60889. // A mapping of the button name to glTF model node name
  60890. // that should be transformed by button value.
  60891. buttonMeshNames: {
  60892. 'trigger': 'SELECT',
  60893. 'menu': 'MENU',
  60894. 'grip': 'GRASP',
  60895. 'thumbstick': 'THUMBSTICK_PRESS',
  60896. 'trackpad': 'TOUCHPAD_PRESS'
  60897. },
  60898. // This mapping is used to translate from the Motion Controller to Babylon semantics
  60899. buttonObservableNames: {
  60900. 'trigger': 'onTriggerStateChangedObservable',
  60901. 'menu': 'onSecondaryButtonStateChangedObservable',
  60902. 'grip': 'onMainButtonStateChangedObservable',
  60903. 'thumbstick': 'onPadStateChangedObservable',
  60904. 'trackpad': 'onTrackpadChangedObservable'
  60905. },
  60906. // A mapping of the axis name to glTF model node name
  60907. // that should be transformed by axis value.
  60908. // This array mirrors the browserGamepad.axes array, such that
  60909. // the mesh corresponding to axis 0 is in this array index 0.
  60910. axisMeshNames: [
  60911. 'THUMBSTICK_X',
  60912. 'THUMBSTICK_Y',
  60913. 'TOUCHPAD_TOUCH_X',
  60914. 'TOUCHPAD_TOUCH_Y'
  60915. ],
  60916. pointingPoseMeshName: 'POINTING_POSE'
  60917. };
  60918. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  60919. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  60920. _this.trackpad = { x: 0, y: 0 };
  60921. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  60922. _this._loadedMeshInfo = null;
  60923. return _this;
  60924. }
  60925. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  60926. get: function () {
  60927. return this.onTriggerStateChangedObservable;
  60928. },
  60929. enumerable: true,
  60930. configurable: true
  60931. });
  60932. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  60933. get: function () {
  60934. return this.onSecondaryButtonStateChangedObservable;
  60935. },
  60936. enumerable: true,
  60937. configurable: true
  60938. });
  60939. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  60940. get: function () {
  60941. return this.onMainButtonStateChangedObservable;
  60942. },
  60943. enumerable: true,
  60944. configurable: true
  60945. });
  60946. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  60947. get: function () {
  60948. return this.onPadStateChangedObservable;
  60949. },
  60950. enumerable: true,
  60951. configurable: true
  60952. });
  60953. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  60954. get: function () {
  60955. return this.onTrackpadChangedObservable;
  60956. },
  60957. enumerable: true,
  60958. configurable: true
  60959. });
  60960. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  60961. get: function () {
  60962. return this.onTrackpadValuesChangedObservable;
  60963. },
  60964. enumerable: true,
  60965. configurable: true
  60966. });
  60967. /**
  60968. * Called once per frame by the engine.
  60969. */
  60970. WindowsMotionController.prototype.update = function () {
  60971. _super.prototype.update.call(this);
  60972. // Only need to animate axes if there is a loaded mesh
  60973. if (this._loadedMeshInfo) {
  60974. if (this.browserGamepad.axes) {
  60975. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  60976. this.trackpad.x = this.browserGamepad["axes"][2];
  60977. this.trackpad.y = this.browserGamepad["axes"][3];
  60978. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  60979. }
  60980. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  60981. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  60982. }
  60983. }
  60984. }
  60985. };
  60986. /**
  60987. * Called once for each button that changed state since the last frame
  60988. * @param buttonIdx Which button index changed
  60989. * @param state New state of the button
  60990. * @param changes Which properties on the state changed since last frame
  60991. */
  60992. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  60993. var buttonName = this._mapping.buttons[buttonIdx];
  60994. if (!buttonName) {
  60995. return;
  60996. }
  60997. // Only emit events for buttons that we know how to map from index to name
  60998. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  60999. if (observable) {
  61000. observable.notifyObservers(state);
  61001. }
  61002. this.lerpButtonTransform(buttonName, state.value);
  61003. };
  61004. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  61005. // If there is no loaded mesh, there is nothing to transform.
  61006. if (!this._loadedMeshInfo) {
  61007. return;
  61008. }
  61009. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  61010. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  61011. return;
  61012. }
  61013. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  61014. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  61015. };
  61016. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  61017. if (!this._loadedMeshInfo) {
  61018. return;
  61019. }
  61020. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  61021. if (!meshInfo) {
  61022. return;
  61023. }
  61024. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  61025. return;
  61026. }
  61027. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  61028. var lerpValue = axisValue * 0.5 + 0.5;
  61029. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  61030. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  61031. };
  61032. /**
  61033. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  61034. * @param scene scene in which to add meshes
  61035. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  61036. */
  61037. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  61038. var _this = this;
  61039. if (forceDefault === void 0) { forceDefault = false; }
  61040. var path;
  61041. var filename;
  61042. // Checking if GLB loader is present
  61043. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  61044. // Determine the device specific folder based on the ID suffix
  61045. var device = 'default';
  61046. if (this.id && !forceDefault) {
  61047. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  61048. device = ((match && match[0]) || device);
  61049. }
  61050. // Hand
  61051. if (this.hand === 'left') {
  61052. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  61053. }
  61054. else {
  61055. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  61056. }
  61057. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  61058. }
  61059. else {
  61060. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  61061. path = BABYLON.GenericController.MODEL_BASE_URL;
  61062. filename = BABYLON.GenericController.MODEL_FILENAME;
  61063. }
  61064. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  61065. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  61066. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  61067. if (!_this._loadedMeshInfo) {
  61068. return;
  61069. }
  61070. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  61071. _this.attachToMesh(_this._defaultModel);
  61072. if (meshLoaded) {
  61073. meshLoaded(_this._defaultModel);
  61074. }
  61075. }, null, function (scene, message) {
  61076. BABYLON.Tools.Log(message);
  61077. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  61078. if (!forceDefault) {
  61079. _this.initControllerMesh(scene, meshLoaded, true);
  61080. }
  61081. });
  61082. };
  61083. /**
  61084. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  61085. * can be transformed by button presses and axes values, based on this._mapping.
  61086. *
  61087. * @param scene scene in which the meshes exist
  61088. * @param meshes list of meshes that make up the controller model to process
  61089. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  61090. */
  61091. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  61092. var loadedMeshInfo = null;
  61093. // Create a new mesh to contain the glTF hierarchy
  61094. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  61095. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  61096. var childMesh = null;
  61097. for (var i = 0; i < meshes.length; i++) {
  61098. var mesh = meshes[i];
  61099. if (!mesh.parent) {
  61100. // Exclude controller meshes from picking results
  61101. mesh.isPickable = false;
  61102. // Handle root node, attach to the new parentMesh
  61103. childMesh = mesh;
  61104. break;
  61105. }
  61106. }
  61107. if (childMesh) {
  61108. childMesh.setParent(parentMesh);
  61109. // Create our mesh info. Note that this method will always return non-null.
  61110. loadedMeshInfo = this.createMeshInfo(parentMesh);
  61111. }
  61112. else {
  61113. BABYLON.Tools.Warn('Could not find root node in model file.');
  61114. }
  61115. return loadedMeshInfo;
  61116. };
  61117. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  61118. var loadedMeshInfo = new LoadedMeshInfo();
  61119. var i;
  61120. loadedMeshInfo.rootNode = rootNode;
  61121. // Reset the caches
  61122. loadedMeshInfo.buttonMeshes = {};
  61123. loadedMeshInfo.axisMeshes = {};
  61124. // Button Meshes
  61125. for (i = 0; i < this._mapping.buttons.length; i++) {
  61126. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  61127. if (!buttonMeshName) {
  61128. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  61129. continue;
  61130. }
  61131. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  61132. if (!buttonMesh) {
  61133. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  61134. continue;
  61135. }
  61136. var buttonMeshInfo = {
  61137. index: i,
  61138. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  61139. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  61140. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  61141. };
  61142. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  61143. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  61144. }
  61145. else {
  61146. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  61147. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  61148. '(VALUE: ' + !!buttonMeshInfo.value +
  61149. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  61150. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  61151. ')');
  61152. }
  61153. }
  61154. // Axis Meshes
  61155. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  61156. var axisMeshName = this._mapping.axisMeshNames[i];
  61157. if (!axisMeshName) {
  61158. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  61159. continue;
  61160. }
  61161. var axisMesh = getChildByName(rootNode, axisMeshName);
  61162. if (!axisMesh) {
  61163. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  61164. continue;
  61165. }
  61166. var axisMeshInfo = {
  61167. index: i,
  61168. value: getImmediateChildByName(axisMesh, 'VALUE'),
  61169. min: getImmediateChildByName(axisMesh, 'MIN'),
  61170. max: getImmediateChildByName(axisMesh, 'MAX')
  61171. };
  61172. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  61173. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  61174. }
  61175. else {
  61176. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  61177. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  61178. '(VALUE: ' + !!axisMeshInfo.value +
  61179. ', MIN: ' + !!axisMeshInfo.min +
  61180. ', MAX:' + !!axisMeshInfo.max +
  61181. ')');
  61182. }
  61183. }
  61184. // Pointing Ray
  61185. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  61186. if (!loadedMeshInfo.pointingPoseNode) {
  61187. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  61188. }
  61189. return loadedMeshInfo;
  61190. // Look through all children recursively. This will return null if no mesh exists with the given name.
  61191. function getChildByName(node, name) {
  61192. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  61193. }
  61194. // Look through only immediate children. This will return null if no mesh exists with the given name.
  61195. function getImmediateChildByName(node, name) {
  61196. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  61197. }
  61198. };
  61199. WindowsMotionController.prototype.getForwardRay = function (length) {
  61200. if (length === void 0) { length = 100; }
  61201. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  61202. return _super.prototype.getForwardRay.call(this, length);
  61203. }
  61204. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  61205. var origin = m.getTranslation();
  61206. var forward = new BABYLON.Vector3(0, 0, -1);
  61207. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  61208. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  61209. return new BABYLON.Ray(origin, direction, length);
  61210. };
  61211. WindowsMotionController.prototype.dispose = function () {
  61212. _super.prototype.dispose.call(this);
  61213. this.onTrackpadChangedObservable.clear();
  61214. };
  61215. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  61216. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  61217. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  61218. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  61219. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  61220. return WindowsMotionController;
  61221. }(BABYLON.WebVRController));
  61222. BABYLON.WindowsMotionController = WindowsMotionController;
  61223. })(BABYLON || (BABYLON = {}));
  61224. //# sourceMappingURL=babylon.windowsMotionController.js.map
  61225. var BABYLON;
  61226. (function (BABYLON) {
  61227. var GearVRController = /** @class */ (function (_super) {
  61228. __extends(GearVRController, _super);
  61229. function GearVRController(vrGamepad) {
  61230. var _this = _super.call(this, vrGamepad) || this;
  61231. _this._buttonIndexToObservableNameMap = [
  61232. 'onTrackpadChangedObservable',
  61233. 'onTriggerStateChangedObservable' // Trigger
  61234. ];
  61235. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  61236. return _this;
  61237. }
  61238. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  61239. var _this = this;
  61240. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  61241. _this._defaultModel = newMeshes[1];
  61242. _this.attachToMesh(_this._defaultModel);
  61243. if (meshLoaded) {
  61244. meshLoaded(_this._defaultModel);
  61245. }
  61246. });
  61247. };
  61248. GearVRController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  61249. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  61250. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  61251. // Only emit events for buttons that we know how to map from index to observable
  61252. var observable = this[observableName];
  61253. if (observable) {
  61254. observable.notifyObservers(state);
  61255. }
  61256. }
  61257. };
  61258. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  61259. GearVRController.MODEL_FILENAME = 'generic.babylon';
  61260. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  61261. return GearVRController;
  61262. }(BABYLON.WebVRController));
  61263. BABYLON.GearVRController = GearVRController;
  61264. })(BABYLON || (BABYLON = {}));
  61265. //# sourceMappingURL=babylon.gearVRController.js.map
  61266. var BABYLON;
  61267. (function (BABYLON) {
  61268. var FollowCamera = /** @class */ (function (_super) {
  61269. __extends(FollowCamera, _super);
  61270. function FollowCamera(name, position, scene, lockedTarget) {
  61271. if (lockedTarget === void 0) { lockedTarget = null; }
  61272. var _this = _super.call(this, name, position, scene) || this;
  61273. _this.radius = 12;
  61274. _this.rotationOffset = 0;
  61275. _this.heightOffset = 4;
  61276. _this.cameraAcceleration = 0.05;
  61277. _this.maxCameraSpeed = 20;
  61278. _this.lockedTarget = lockedTarget;
  61279. return _this;
  61280. }
  61281. FollowCamera.prototype.getRadians = function (degrees) {
  61282. return degrees * Math.PI / 180;
  61283. };
  61284. FollowCamera.prototype.follow = function (cameraTarget) {
  61285. if (!cameraTarget)
  61286. return;
  61287. var yRotation;
  61288. if (cameraTarget.rotationQuaternion) {
  61289. var rotMatrix = new BABYLON.Matrix();
  61290. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  61291. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  61292. }
  61293. else {
  61294. yRotation = cameraTarget.rotation.y;
  61295. }
  61296. var radians = this.getRadians(this.rotationOffset) + yRotation;
  61297. var targetPosition = cameraTarget.getAbsolutePosition();
  61298. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  61299. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  61300. var dx = targetX - this.position.x;
  61301. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  61302. var dz = (targetZ) - this.position.z;
  61303. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  61304. var vy = dy * this.cameraAcceleration;
  61305. var vz = dz * this.cameraAcceleration * 2;
  61306. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  61307. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  61308. }
  61309. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  61310. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  61311. }
  61312. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  61313. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  61314. }
  61315. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  61316. this.setTarget(targetPosition);
  61317. };
  61318. FollowCamera.prototype._checkInputs = function () {
  61319. _super.prototype._checkInputs.call(this);
  61320. if (this.lockedTarget) {
  61321. this.follow(this.lockedTarget);
  61322. }
  61323. };
  61324. FollowCamera.prototype.getClassName = function () {
  61325. return "FollowCamera";
  61326. };
  61327. __decorate([
  61328. BABYLON.serialize()
  61329. ], FollowCamera.prototype, "radius", void 0);
  61330. __decorate([
  61331. BABYLON.serialize()
  61332. ], FollowCamera.prototype, "rotationOffset", void 0);
  61333. __decorate([
  61334. BABYLON.serialize()
  61335. ], FollowCamera.prototype, "heightOffset", void 0);
  61336. __decorate([
  61337. BABYLON.serialize()
  61338. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  61339. __decorate([
  61340. BABYLON.serialize()
  61341. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  61342. __decorate([
  61343. BABYLON.serializeAsMeshReference("lockedTargetId")
  61344. ], FollowCamera.prototype, "lockedTarget", void 0);
  61345. return FollowCamera;
  61346. }(BABYLON.TargetCamera));
  61347. BABYLON.FollowCamera = FollowCamera;
  61348. var ArcFollowCamera = /** @class */ (function (_super) {
  61349. __extends(ArcFollowCamera, _super);
  61350. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  61351. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  61352. _this.alpha = alpha;
  61353. _this.beta = beta;
  61354. _this.radius = radius;
  61355. _this.target = target;
  61356. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  61357. _this.follow();
  61358. return _this;
  61359. }
  61360. ArcFollowCamera.prototype.follow = function () {
  61361. if (!this.target) {
  61362. return;
  61363. }
  61364. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  61365. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  61366. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  61367. var targetPosition = this.target.getAbsolutePosition();
  61368. this.position = targetPosition.add(this._cartesianCoordinates);
  61369. this.setTarget(targetPosition);
  61370. };
  61371. ArcFollowCamera.prototype._checkInputs = function () {
  61372. _super.prototype._checkInputs.call(this);
  61373. this.follow();
  61374. };
  61375. ArcFollowCamera.prototype.getClassName = function () {
  61376. return "ArcFollowCamera";
  61377. };
  61378. return ArcFollowCamera;
  61379. }(BABYLON.TargetCamera));
  61380. BABYLON.ArcFollowCamera = ArcFollowCamera;
  61381. })(BABYLON || (BABYLON = {}));
  61382. //# sourceMappingURL=babylon.followCamera.js.map
  61383. var BABYLON;
  61384. (function (BABYLON) {
  61385. // We're mainly based on the logic defined into the FreeCamera code
  61386. var UniversalCamera = /** @class */ (function (_super) {
  61387. __extends(UniversalCamera, _super);
  61388. //-- end properties for backward compatibility for inputs
  61389. function UniversalCamera(name, position, scene) {
  61390. var _this = _super.call(this, name, position, scene) || this;
  61391. _this.inputs.addGamepad();
  61392. return _this;
  61393. }
  61394. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  61395. //-- Begin properties for backward compatibility for inputs
  61396. get: function () {
  61397. var gamepad = this.inputs.attached["gamepad"];
  61398. if (gamepad)
  61399. return gamepad.gamepadAngularSensibility;
  61400. return 0;
  61401. },
  61402. set: function (value) {
  61403. var gamepad = this.inputs.attached["gamepad"];
  61404. if (gamepad)
  61405. gamepad.gamepadAngularSensibility = value;
  61406. },
  61407. enumerable: true,
  61408. configurable: true
  61409. });
  61410. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  61411. get: function () {
  61412. var gamepad = this.inputs.attached["gamepad"];
  61413. if (gamepad)
  61414. return gamepad.gamepadMoveSensibility;
  61415. return 0;
  61416. },
  61417. set: function (value) {
  61418. var gamepad = this.inputs.attached["gamepad"];
  61419. if (gamepad)
  61420. gamepad.gamepadMoveSensibility = value;
  61421. },
  61422. enumerable: true,
  61423. configurable: true
  61424. });
  61425. UniversalCamera.prototype.getClassName = function () {
  61426. return "UniversalCamera";
  61427. };
  61428. return UniversalCamera;
  61429. }(BABYLON.TouchCamera));
  61430. BABYLON.UniversalCamera = UniversalCamera;
  61431. })(BABYLON || (BABYLON = {}));
  61432. //# sourceMappingURL=babylon.universalCamera.js.map
  61433. var BABYLON;
  61434. (function (BABYLON) {
  61435. // We're mainly based on the logic defined into the FreeCamera code
  61436. var GamepadCamera = /** @class */ (function (_super) {
  61437. __extends(GamepadCamera, _super);
  61438. //-- end properties for backward compatibility for inputs
  61439. function GamepadCamera(name, position, scene) {
  61440. return _super.call(this, name, position, scene) || this;
  61441. }
  61442. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  61443. //-- Begin properties for backward compatibility for inputs
  61444. get: function () {
  61445. var gamepad = this.inputs.attached["gamepad"];
  61446. if (gamepad)
  61447. return gamepad.gamepadAngularSensibility;
  61448. return 0;
  61449. },
  61450. set: function (value) {
  61451. var gamepad = this.inputs.attached["gamepad"];
  61452. if (gamepad)
  61453. gamepad.gamepadAngularSensibility = value;
  61454. },
  61455. enumerable: true,
  61456. configurable: true
  61457. });
  61458. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  61459. get: function () {
  61460. var gamepad = this.inputs.attached["gamepad"];
  61461. if (gamepad)
  61462. return gamepad.gamepadMoveSensibility;
  61463. return 0;
  61464. },
  61465. set: function (value) {
  61466. var gamepad = this.inputs.attached["gamepad"];
  61467. if (gamepad)
  61468. gamepad.gamepadMoveSensibility = value;
  61469. },
  61470. enumerable: true,
  61471. configurable: true
  61472. });
  61473. GamepadCamera.prototype.getClassName = function () {
  61474. return "GamepadCamera";
  61475. };
  61476. return GamepadCamera;
  61477. }(BABYLON.UniversalCamera));
  61478. BABYLON.GamepadCamera = GamepadCamera;
  61479. })(BABYLON || (BABYLON = {}));
  61480. //# sourceMappingURL=babylon.gamepadCamera.js.map
  61481. var BABYLON;
  61482. (function (BABYLON) {
  61483. var PostProcessRenderPipelineManager = /** @class */ (function () {
  61484. function PostProcessRenderPipelineManager() {
  61485. this._renderPipelines = {};
  61486. }
  61487. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  61488. this._renderPipelines[renderPipeline._name] = renderPipeline;
  61489. };
  61490. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  61491. if (unique === void 0) { unique = false; }
  61492. var renderPipeline = this._renderPipelines[renderPipelineName];
  61493. if (!renderPipeline) {
  61494. return;
  61495. }
  61496. renderPipeline._attachCameras(cameras, unique);
  61497. };
  61498. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  61499. var renderPipeline = this._renderPipelines[renderPipelineName];
  61500. if (!renderPipeline) {
  61501. return;
  61502. }
  61503. renderPipeline._detachCameras(cameras);
  61504. };
  61505. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  61506. var renderPipeline = this._renderPipelines[renderPipelineName];
  61507. if (!renderPipeline) {
  61508. return;
  61509. }
  61510. renderPipeline._enableEffect(renderEffectName, cameras);
  61511. };
  61512. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  61513. var renderPipeline = this._renderPipelines[renderPipelineName];
  61514. if (!renderPipeline) {
  61515. return;
  61516. }
  61517. renderPipeline._disableEffect(renderEffectName, cameras);
  61518. };
  61519. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  61520. var renderPipeline = this._renderPipelines[renderPipelineName];
  61521. if (!renderPipeline) {
  61522. return;
  61523. }
  61524. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  61525. };
  61526. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  61527. var renderPipeline = this._renderPipelines[renderPipelineName];
  61528. if (!renderPipeline) {
  61529. return;
  61530. }
  61531. renderPipeline._disableDisplayOnlyPass(cameras);
  61532. };
  61533. PostProcessRenderPipelineManager.prototype.update = function () {
  61534. for (var renderPipelineName in this._renderPipelines) {
  61535. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  61536. var pipeline = this._renderPipelines[renderPipelineName];
  61537. if (!pipeline.isSupported) {
  61538. pipeline.dispose();
  61539. delete this._renderPipelines[renderPipelineName];
  61540. }
  61541. else {
  61542. pipeline._update();
  61543. }
  61544. }
  61545. }
  61546. };
  61547. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  61548. for (var renderPipelineName in this._renderPipelines) {
  61549. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  61550. var pipeline = this._renderPipelines[renderPipelineName];
  61551. pipeline._rebuild();
  61552. }
  61553. }
  61554. };
  61555. PostProcessRenderPipelineManager.prototype.dispose = function () {
  61556. for (var renderPipelineName in this._renderPipelines) {
  61557. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  61558. var pipeline = this._renderPipelines[renderPipelineName];
  61559. pipeline.dispose();
  61560. }
  61561. }
  61562. };
  61563. return PostProcessRenderPipelineManager;
  61564. }());
  61565. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  61566. })(BABYLON || (BABYLON = {}));
  61567. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  61568. var BABYLON;
  61569. (function (BABYLON) {
  61570. var PostProcessRenderPass = /** @class */ (function () {
  61571. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  61572. this._refCount = 0;
  61573. this._name = name;
  61574. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  61575. this.setRenderList(renderList);
  61576. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  61577. this._renderTexture.onAfterRenderObservable.add(afterRender);
  61578. this._scene = scene;
  61579. this._renderList = renderList;
  61580. }
  61581. // private
  61582. PostProcessRenderPass.prototype._incRefCount = function () {
  61583. if (this._refCount === 0) {
  61584. this._scene.customRenderTargets.push(this._renderTexture);
  61585. }
  61586. return ++this._refCount;
  61587. };
  61588. PostProcessRenderPass.prototype._decRefCount = function () {
  61589. this._refCount--;
  61590. if (this._refCount <= 0) {
  61591. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  61592. }
  61593. return this._refCount;
  61594. };
  61595. PostProcessRenderPass.prototype._update = function () {
  61596. this.setRenderList(this._renderList);
  61597. };
  61598. // public
  61599. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  61600. this._renderTexture.renderList = renderList;
  61601. };
  61602. PostProcessRenderPass.prototype.getRenderTexture = function () {
  61603. return this._renderTexture;
  61604. };
  61605. return PostProcessRenderPass;
  61606. }());
  61607. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  61608. })(BABYLON || (BABYLON = {}));
  61609. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  61610. var BABYLON;
  61611. (function (BABYLON) {
  61612. var PostProcessRenderEffect = /** @class */ (function () {
  61613. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  61614. this._name = name;
  61615. this._singleInstance = singleInstance || true;
  61616. this._getPostProcess = getPostProcess;
  61617. this._cameras = {};
  61618. this._indicesForCamera = {};
  61619. this._postProcesses = {};
  61620. this._renderPasses = {};
  61621. this._renderEffectAsPasses = {};
  61622. }
  61623. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  61624. get: function () {
  61625. for (var index in this._postProcesses) {
  61626. if (!this._postProcesses[index].isSupported) {
  61627. return false;
  61628. }
  61629. }
  61630. return true;
  61631. },
  61632. enumerable: true,
  61633. configurable: true
  61634. });
  61635. PostProcessRenderEffect.prototype._update = function () {
  61636. for (var renderPassName in this._renderPasses) {
  61637. this._renderPasses[renderPassName]._update();
  61638. }
  61639. };
  61640. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  61641. this._renderPasses[renderPass._name] = renderPass;
  61642. this._linkParameters();
  61643. };
  61644. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  61645. delete this._renderPasses[renderPass._name];
  61646. this._linkParameters();
  61647. };
  61648. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  61649. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  61650. this._linkParameters();
  61651. };
  61652. PostProcessRenderEffect.prototype.getPass = function (passName) {
  61653. for (var renderPassName in this._renderPasses) {
  61654. if (renderPassName === passName) {
  61655. return this._renderPasses[passName];
  61656. }
  61657. }
  61658. return null;
  61659. };
  61660. PostProcessRenderEffect.prototype.emptyPasses = function () {
  61661. this._renderPasses = {};
  61662. this._linkParameters();
  61663. };
  61664. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  61665. var cameraKey;
  61666. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  61667. if (!cams) {
  61668. return;
  61669. }
  61670. for (var i = 0; i < cams.length; i++) {
  61671. var camera = cams[i];
  61672. var cameraName = camera.name;
  61673. if (this._singleInstance) {
  61674. cameraKey = 0;
  61675. }
  61676. else {
  61677. cameraKey = cameraName;
  61678. }
  61679. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  61680. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  61681. if (!this._indicesForCamera[cameraName]) {
  61682. this._indicesForCamera[cameraName] = [];
  61683. }
  61684. this._indicesForCamera[cameraName].push(index);
  61685. if (!this._cameras[cameraName]) {
  61686. this._cameras[cameraName] = camera;
  61687. }
  61688. for (var passName in this._renderPasses) {
  61689. this._renderPasses[passName]._incRefCount();
  61690. }
  61691. }
  61692. this._linkParameters();
  61693. };
  61694. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  61695. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  61696. if (!cams) {
  61697. return;
  61698. }
  61699. for (var i = 0; i < cams.length; i++) {
  61700. var camera = cams[i];
  61701. var cameraName = camera.name;
  61702. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  61703. if (this._cameras[cameraName]) {
  61704. //this._indicesForCamera.splice(index, 1);
  61705. this._cameras[cameraName] = null;
  61706. }
  61707. for (var passName in this._renderPasses) {
  61708. this._renderPasses[passName]._decRefCount();
  61709. }
  61710. }
  61711. };
  61712. PostProcessRenderEffect.prototype._enable = function (cameras) {
  61713. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  61714. if (!cams) {
  61715. return;
  61716. }
  61717. for (var i = 0; i < cams.length; i++) {
  61718. var camera = cams[i];
  61719. var cameraName = camera.name;
  61720. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  61721. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  61722. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  61723. }
  61724. }
  61725. for (var passName in this._renderPasses) {
  61726. this._renderPasses[passName]._incRefCount();
  61727. }
  61728. }
  61729. };
  61730. PostProcessRenderEffect.prototype._disable = function (cameras) {
  61731. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  61732. if (!cams) {
  61733. return;
  61734. }
  61735. for (var i = 0; i < cams.length; i++) {
  61736. var camera = cams[i];
  61737. var cameraName = camera.Name;
  61738. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  61739. for (var passName in this._renderPasses) {
  61740. this._renderPasses[passName]._decRefCount();
  61741. }
  61742. }
  61743. };
  61744. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  61745. if (this._singleInstance) {
  61746. return this._postProcesses[0];
  61747. }
  61748. else {
  61749. if (!camera) {
  61750. return null;
  61751. }
  61752. return this._postProcesses[camera.name];
  61753. }
  61754. };
  61755. PostProcessRenderEffect.prototype._linkParameters = function () {
  61756. var _this = this;
  61757. for (var index in this._postProcesses) {
  61758. if (this.applyParameters) {
  61759. this.applyParameters(this._postProcesses[index]);
  61760. }
  61761. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  61762. _this._linkTextures(effect);
  61763. });
  61764. }
  61765. };
  61766. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  61767. for (var renderPassName in this._renderPasses) {
  61768. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  61769. }
  61770. for (var renderEffectName in this._renderEffectAsPasses) {
  61771. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  61772. }
  61773. };
  61774. return PostProcessRenderEffect;
  61775. }());
  61776. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  61777. })(BABYLON || (BABYLON = {}));
  61778. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  61779. var BABYLON;
  61780. (function (BABYLON) {
  61781. var PostProcessRenderPipeline = /** @class */ (function () {
  61782. function PostProcessRenderPipeline(engine, name) {
  61783. this._engine = engine;
  61784. this._name = name;
  61785. this._renderEffects = {};
  61786. this._renderEffectsForIsolatedPass = new Array();
  61787. this._cameras = [];
  61788. }
  61789. PostProcessRenderPipeline.prototype.getClassName = function () {
  61790. return "PostProcessRenderPipeline";
  61791. };
  61792. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  61793. get: function () {
  61794. for (var renderEffectName in this._renderEffects) {
  61795. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  61796. if (!this._renderEffects[renderEffectName].isSupported) {
  61797. return false;
  61798. }
  61799. }
  61800. }
  61801. return true;
  61802. },
  61803. enumerable: true,
  61804. configurable: true
  61805. });
  61806. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  61807. this._renderEffects[renderEffect._name] = renderEffect;
  61808. };
  61809. // private
  61810. PostProcessRenderPipeline.prototype._rebuild = function () {
  61811. };
  61812. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  61813. var renderEffects = this._renderEffects[renderEffectName];
  61814. if (!renderEffects) {
  61815. return;
  61816. }
  61817. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  61818. };
  61819. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  61820. var renderEffects = this._renderEffects[renderEffectName];
  61821. if (!renderEffects) {
  61822. return;
  61823. }
  61824. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  61825. };
  61826. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  61827. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  61828. if (!cams) {
  61829. return;
  61830. }
  61831. var indicesToDelete = [];
  61832. var i;
  61833. for (i = 0; i < cams.length; i++) {
  61834. var camera = cams[i];
  61835. var cameraName = camera.name;
  61836. if (this._cameras.indexOf(camera) === -1) {
  61837. this._cameras[cameraName] = camera;
  61838. }
  61839. else if (unique) {
  61840. indicesToDelete.push(i);
  61841. }
  61842. }
  61843. for (i = 0; i < indicesToDelete.length; i++) {
  61844. cameras.splice(indicesToDelete[i], 1);
  61845. }
  61846. for (var renderEffectName in this._renderEffects) {
  61847. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  61848. this._renderEffects[renderEffectName]._attachCameras(cams);
  61849. }
  61850. }
  61851. };
  61852. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  61853. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  61854. if (!cams) {
  61855. return;
  61856. }
  61857. for (var renderEffectName in this._renderEffects) {
  61858. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  61859. this._renderEffects[renderEffectName]._detachCameras(cams);
  61860. }
  61861. }
  61862. for (var i = 0; i < cams.length; i++) {
  61863. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  61864. }
  61865. };
  61866. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  61867. var _this = this;
  61868. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  61869. if (!cams) {
  61870. return;
  61871. }
  61872. var pass = null;
  61873. var renderEffectName;
  61874. for (renderEffectName in this._renderEffects) {
  61875. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  61876. pass = this._renderEffects[renderEffectName].getPass(passName);
  61877. if (pass != null) {
  61878. break;
  61879. }
  61880. }
  61881. }
  61882. if (pass === null) {
  61883. return;
  61884. }
  61885. for (renderEffectName in this._renderEffects) {
  61886. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  61887. this._renderEffects[renderEffectName]._disable(cams);
  61888. }
  61889. }
  61890. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  61891. for (var i = 0; i < cams.length; i++) {
  61892. var camera = cams[i];
  61893. var cameraName = camera.name;
  61894. 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); });
  61895. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  61896. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  61897. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  61898. }
  61899. };
  61900. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  61901. var _this = this;
  61902. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  61903. if (!cams) {
  61904. return;
  61905. }
  61906. for (var i = 0; i < cams.length; i++) {
  61907. var camera = cams[i];
  61908. var cameraName = camera.name;
  61909. 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); });
  61910. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  61911. }
  61912. for (var renderEffectName in this._renderEffects) {
  61913. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  61914. this._renderEffects[renderEffectName]._enable(cams);
  61915. }
  61916. }
  61917. };
  61918. PostProcessRenderPipeline.prototype._update = function () {
  61919. for (var renderEffectName in this._renderEffects) {
  61920. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  61921. this._renderEffects[renderEffectName]._update();
  61922. }
  61923. }
  61924. for (var i = 0; i < this._cameras.length; i++) {
  61925. var cameraName = this._cameras[i].name;
  61926. if (this._renderEffectsForIsolatedPass[cameraName]) {
  61927. this._renderEffectsForIsolatedPass[cameraName]._update();
  61928. }
  61929. }
  61930. };
  61931. PostProcessRenderPipeline.prototype._reset = function () {
  61932. this._renderEffects = {};
  61933. this._renderEffectsForIsolatedPass = new Array();
  61934. };
  61935. PostProcessRenderPipeline.prototype.dispose = function () {
  61936. // Must be implemented by children
  61937. };
  61938. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  61939. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  61940. __decorate([
  61941. BABYLON.serialize()
  61942. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  61943. return PostProcessRenderPipeline;
  61944. }());
  61945. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  61946. })(BABYLON || (BABYLON = {}));
  61947. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  61948. var BABYLON;
  61949. (function (BABYLON) {
  61950. var DepthRenderer = /** @class */ (function () {
  61951. function DepthRenderer(scene, type) {
  61952. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  61953. var _this = this;
  61954. this._scene = scene;
  61955. var engine = scene.getEngine();
  61956. // Render target
  61957. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  61958. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61959. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61960. this._depthMap.refreshRate = 1;
  61961. this._depthMap.renderParticles = false;
  61962. this._depthMap.renderList = null;
  61963. // set default depth value to 1.0 (far away)
  61964. this._depthMap.onClearObservable.add(function (engine) {
  61965. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  61966. });
  61967. // Custom render function
  61968. var renderSubMesh = function (subMesh) {
  61969. var mesh = subMesh.getRenderingMesh();
  61970. var scene = _this._scene;
  61971. var engine = scene.getEngine();
  61972. var material = subMesh.getMaterial();
  61973. if (!material) {
  61974. return;
  61975. }
  61976. // Culling and reverse (right handed system)
  61977. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  61978. // Managing instances
  61979. var batch = mesh._getInstancesRenderList(subMesh._id);
  61980. if (batch.mustReturn) {
  61981. return;
  61982. }
  61983. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  61984. if (_this.isReady(subMesh, hardwareInstancedRendering) && scene.activeCamera) {
  61985. engine.enableEffect(_this._effect);
  61986. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  61987. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  61988. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  61989. // Alpha test
  61990. if (material && material.needAlphaTesting()) {
  61991. var alphaTexture = material.getAlphaTestTexture();
  61992. if (alphaTexture) {
  61993. _this._effect.setTexture("diffuseSampler", alphaTexture);
  61994. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  61995. }
  61996. }
  61997. // Bones
  61998. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  61999. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  62000. }
  62001. // Draw
  62002. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  62003. }
  62004. };
  62005. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  62006. var index;
  62007. if (depthOnlySubMeshes.length) {
  62008. engine.setColorWrite(false);
  62009. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  62010. renderSubMesh(depthOnlySubMeshes.data[index]);
  62011. }
  62012. engine.setColorWrite(true);
  62013. }
  62014. for (index = 0; index < opaqueSubMeshes.length; index++) {
  62015. renderSubMesh(opaqueSubMeshes.data[index]);
  62016. }
  62017. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  62018. renderSubMesh(alphaTestSubMeshes.data[index]);
  62019. }
  62020. };
  62021. }
  62022. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  62023. var material = subMesh.getMaterial();
  62024. if (material.disableDepthWrite) {
  62025. return false;
  62026. }
  62027. var defines = [];
  62028. var attribs = [BABYLON.VertexBuffer.PositionKind];
  62029. var mesh = subMesh.getMesh();
  62030. // Alpha test
  62031. if (material && material.needAlphaTesting()) {
  62032. defines.push("#define ALPHATEST");
  62033. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  62034. attribs.push(BABYLON.VertexBuffer.UVKind);
  62035. defines.push("#define UV1");
  62036. }
  62037. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  62038. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  62039. defines.push("#define UV2");
  62040. }
  62041. }
  62042. // Bones
  62043. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  62044. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  62045. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  62046. if (mesh.numBoneInfluencers > 4) {
  62047. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  62048. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  62049. }
  62050. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  62051. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  62052. }
  62053. else {
  62054. defines.push("#define NUM_BONE_INFLUENCERS 0");
  62055. }
  62056. // Instances
  62057. if (useInstances) {
  62058. defines.push("#define INSTANCES");
  62059. attribs.push("world0");
  62060. attribs.push("world1");
  62061. attribs.push("world2");
  62062. attribs.push("world3");
  62063. }
  62064. // Get correct effect
  62065. var join = defines.join("\n");
  62066. if (this._cachedDefines !== join) {
  62067. this._cachedDefines = join;
  62068. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  62069. }
  62070. return this._effect.isReady();
  62071. };
  62072. DepthRenderer.prototype.getDepthMap = function () {
  62073. return this._depthMap;
  62074. };
  62075. // Methods
  62076. DepthRenderer.prototype.dispose = function () {
  62077. this._depthMap.dispose();
  62078. };
  62079. return DepthRenderer;
  62080. }());
  62081. BABYLON.DepthRenderer = DepthRenderer;
  62082. })(BABYLON || (BABYLON = {}));
  62083. //# sourceMappingURL=babylon.depthRenderer.js.map
  62084. var BABYLON;
  62085. (function (BABYLON) {
  62086. var SSAORenderingPipeline = /** @class */ (function (_super) {
  62087. __extends(SSAORenderingPipeline, _super);
  62088. /**
  62089. * @constructor
  62090. * @param {string} name - The rendering pipeline name
  62091. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  62092. * @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 }
  62093. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  62094. */
  62095. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  62096. var _this = _super.call(this, scene.getEngine(), name) || this;
  62097. // Members
  62098. /**
  62099. * The PassPostProcess id in the pipeline that contains the original scene color
  62100. * @type {string}
  62101. */
  62102. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  62103. /**
  62104. * The SSAO PostProcess id in the pipeline
  62105. * @type {string}
  62106. */
  62107. _this.SSAORenderEffect = "SSAORenderEffect";
  62108. /**
  62109. * The horizontal blur PostProcess id in the pipeline
  62110. * @type {string}
  62111. */
  62112. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  62113. /**
  62114. * The vertical blur PostProcess id in the pipeline
  62115. * @type {string}
  62116. */
  62117. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  62118. /**
  62119. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  62120. * @type {string}
  62121. */
  62122. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  62123. /**
  62124. * The output strength of the SSAO post-process. Default value is 1.0.
  62125. * @type {number}
  62126. */
  62127. _this.totalStrength = 1.0;
  62128. /**
  62129. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  62130. * @type {number}
  62131. */
  62132. _this.radius = 0.0001;
  62133. /**
  62134. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  62135. * Must not be equal to fallOff and superior to fallOff.
  62136. * Default value is 0.975
  62137. * @type {number}
  62138. */
  62139. _this.area = 0.0075;
  62140. /**
  62141. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  62142. * Must not be equal to area and inferior to area.
  62143. * Default value is 0.0
  62144. * @type {number}
  62145. */
  62146. _this.fallOff = 0.000001;
  62147. /**
  62148. * The base color of the SSAO post-process
  62149. * The final result is "base + ssao" between [0, 1]
  62150. * @type {number}
  62151. */
  62152. _this.base = 0.5;
  62153. _this._firstUpdate = true;
  62154. _this._scene = scene;
  62155. // Set up assets
  62156. _this._createRandomTexture();
  62157. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  62158. var ssaoRatio = ratio.ssaoRatio || ratio;
  62159. var combineRatio = ratio.combineRatio || ratio;
  62160. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  62161. _this._createSSAOPostProcess(ssaoRatio);
  62162. _this._createBlurPostProcess(ssaoRatio);
  62163. _this._createSSAOCombinePostProcess(combineRatio);
  62164. // Set up pipeline
  62165. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  62166. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  62167. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  62168. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  62169. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  62170. // Finish
  62171. scene.postProcessRenderPipelineManager.addPipeline(_this);
  62172. if (cameras)
  62173. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  62174. return _this;
  62175. }
  62176. // Public Methods
  62177. /**
  62178. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  62179. */
  62180. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  62181. if (disableDepthRender === void 0) { disableDepthRender = false; }
  62182. for (var i = 0; i < this._scene.cameras.length; i++) {
  62183. var camera = this._scene.cameras[i];
  62184. this._originalColorPostProcess.dispose(camera);
  62185. this._ssaoPostProcess.dispose(camera);
  62186. this._blurHPostProcess.dispose(camera);
  62187. this._blurVPostProcess.dispose(camera);
  62188. this._ssaoCombinePostProcess.dispose(camera);
  62189. }
  62190. this._randomTexture.dispose();
  62191. if (disableDepthRender)
  62192. this._scene.disableDepthRenderer();
  62193. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  62194. _super.prototype.dispose.call(this);
  62195. };
  62196. // Private Methods
  62197. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  62198. var _this = this;
  62199. var size = 16;
  62200. this._blurHPostProcess = new BABYLON.BlurPostProcess("BlurH", new BABYLON.Vector2(1, 0), size, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  62201. this._blurVPostProcess = new BABYLON.BlurPostProcess("BlurV", new BABYLON.Vector2(0, 1), size, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  62202. this._blurHPostProcess.onActivateObservable.add(function () {
  62203. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  62204. _this._blurHPostProcess.kernel = size * dw;
  62205. });
  62206. this._blurVPostProcess.onActivateObservable.add(function () {
  62207. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  62208. _this._blurVPostProcess.kernel = size * dw;
  62209. });
  62210. };
  62211. SSAORenderingPipeline.prototype._rebuild = function () {
  62212. this._firstUpdate = true;
  62213. _super.prototype._rebuild.call(this);
  62214. };
  62215. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  62216. var _this = this;
  62217. var numSamples = 16;
  62218. var sampleSphere = [
  62219. 0.5381, 0.1856, -0.4319,
  62220. 0.1379, 0.2486, 0.4430,
  62221. 0.3371, 0.5679, -0.0057,
  62222. -0.6999, -0.0451, -0.0019,
  62223. 0.0689, -0.1598, -0.8547,
  62224. 0.0560, 0.0069, -0.1843,
  62225. -0.0146, 0.1402, 0.0762,
  62226. 0.0100, -0.1924, -0.0344,
  62227. -0.3577, -0.5301, -0.4358,
  62228. -0.3169, 0.1063, 0.0158,
  62229. 0.0103, -0.5869, 0.0046,
  62230. -0.0897, -0.4940, 0.3287,
  62231. 0.7119, -0.0154, -0.0918,
  62232. -0.0533, 0.0596, -0.5411,
  62233. 0.0352, -0.0631, 0.5460,
  62234. -0.4776, 0.2847, -0.0271
  62235. ];
  62236. var samplesFactor = 1.0 / numSamples;
  62237. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  62238. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  62239. "area", "fallOff", "base", "range", "viewport"
  62240. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  62241. this._ssaoPostProcess.onApply = function (effect) {
  62242. if (_this._firstUpdate) {
  62243. effect.setArray3("sampleSphere", sampleSphere);
  62244. effect.setFloat("samplesFactor", samplesFactor);
  62245. effect.setFloat("randTextureTiles", 4.0);
  62246. }
  62247. effect.setFloat("totalStrength", _this.totalStrength);
  62248. effect.setFloat("radius", _this.radius);
  62249. effect.setFloat("area", _this.area);
  62250. effect.setFloat("fallOff", _this.fallOff);
  62251. effect.setFloat("base", _this.base);
  62252. effect.setTexture("textureSampler", _this._depthTexture);
  62253. effect.setTexture("randomSampler", _this._randomTexture);
  62254. };
  62255. };
  62256. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  62257. var _this = this;
  62258. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  62259. this._ssaoCombinePostProcess.onApply = function (effect) {
  62260. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  62261. };
  62262. };
  62263. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  62264. var size = 512;
  62265. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  62266. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  62267. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  62268. var context = this._randomTexture.getContext();
  62269. var rand = function (min, max) {
  62270. return Math.random() * (max - min) + min;
  62271. };
  62272. var randVector = BABYLON.Vector3.Zero();
  62273. for (var x = 0; x < size; x++) {
  62274. for (var y = 0; y < size; y++) {
  62275. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  62276. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  62277. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  62278. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  62279. context.fillRect(x, y, 1, 1);
  62280. }
  62281. }
  62282. this._randomTexture.update(false);
  62283. };
  62284. __decorate([
  62285. BABYLON.serialize()
  62286. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  62287. __decorate([
  62288. BABYLON.serialize()
  62289. ], SSAORenderingPipeline.prototype, "radius", void 0);
  62290. __decorate([
  62291. BABYLON.serialize()
  62292. ], SSAORenderingPipeline.prototype, "area", void 0);
  62293. __decorate([
  62294. BABYLON.serialize()
  62295. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  62296. __decorate([
  62297. BABYLON.serialize()
  62298. ], SSAORenderingPipeline.prototype, "base", void 0);
  62299. return SSAORenderingPipeline;
  62300. }(BABYLON.PostProcessRenderPipeline));
  62301. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  62302. })(BABYLON || (BABYLON = {}));
  62303. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  62304. var BABYLON;
  62305. (function (BABYLON) {
  62306. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  62307. __extends(SSAO2RenderingPipeline, _super);
  62308. /**
  62309. * @constructor
  62310. * @param {string} name - The rendering pipeline name
  62311. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  62312. * @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 }
  62313. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  62314. */
  62315. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  62316. var _this = _super.call(this, scene.getEngine(), name) || this;
  62317. // Members
  62318. /**
  62319. * The PassPostProcess id in the pipeline that contains the original scene color
  62320. * @type {string}
  62321. */
  62322. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  62323. /**
  62324. * The SSAO PostProcess id in the pipeline
  62325. * @type {string}
  62326. */
  62327. _this.SSAORenderEffect = "SSAORenderEffect";
  62328. /**
  62329. * The horizontal blur PostProcess id in the pipeline
  62330. * @type {string}
  62331. */
  62332. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  62333. /**
  62334. * The vertical blur PostProcess id in the pipeline
  62335. * @type {string}
  62336. */
  62337. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  62338. /**
  62339. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  62340. * @type {string}
  62341. */
  62342. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  62343. /**
  62344. * The output strength of the SSAO post-process. Default value is 1.0.
  62345. * @type {number}
  62346. */
  62347. _this.totalStrength = 1.0;
  62348. /**
  62349. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  62350. * @type {number}
  62351. */
  62352. _this.maxZ = 100.0;
  62353. /**
  62354. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  62355. * @type {number}
  62356. */
  62357. _this.minZAspect = 0.2;
  62358. /**
  62359. * Number of samples used for the SSAO calculations. Default value is 8
  62360. * @type {number}
  62361. */
  62362. _this._samples = 8;
  62363. /**
  62364. * Are we using bilateral blur ?
  62365. * @type {boolean}
  62366. */
  62367. _this._expensiveBlur = true;
  62368. /**
  62369. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  62370. * @type {number}
  62371. */
  62372. _this.radius = 2.0;
  62373. /**
  62374. * The base color of the SSAO post-process
  62375. * The final result is "base + ssao" between [0, 1]
  62376. * @type {number}
  62377. */
  62378. _this.base = 0.1;
  62379. _this._firstUpdate = true;
  62380. _this._scene = scene;
  62381. if (!_this.isSupported) {
  62382. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  62383. return _this;
  62384. }
  62385. var ssaoRatio = ratio.ssaoRatio || ratio;
  62386. var blurRatio = ratio.blurRatio || ratio;
  62387. // Set up assets
  62388. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  62389. _this._createRandomTexture();
  62390. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  62391. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  62392. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  62393. _this._createSSAOPostProcess(1.0);
  62394. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  62395. _this._createSSAOCombinePostProcess(blurRatio);
  62396. // Set up pipeline
  62397. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  62398. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  62399. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  62400. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  62401. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  62402. // Finish
  62403. scene.postProcessRenderPipelineManager.addPipeline(_this);
  62404. if (cameras)
  62405. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  62406. return _this;
  62407. }
  62408. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  62409. get: function () {
  62410. return this._samples;
  62411. },
  62412. set: function (n) {
  62413. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  62414. this._samples = n;
  62415. this._sampleSphere = this._generateHemisphere();
  62416. this._firstUpdate = true;
  62417. },
  62418. enumerable: true,
  62419. configurable: true
  62420. });
  62421. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  62422. get: function () {
  62423. return this._expensiveBlur;
  62424. },
  62425. set: function (b) {
  62426. 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"]);
  62427. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  62428. this._expensiveBlur = b;
  62429. this._firstUpdate = true;
  62430. },
  62431. enumerable: true,
  62432. configurable: true
  62433. });
  62434. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  62435. /**
  62436. * Support test.
  62437. * @type {boolean}
  62438. */
  62439. get: function () {
  62440. var engine = BABYLON.Engine.LastCreatedEngine;
  62441. if (!engine) {
  62442. return false;
  62443. }
  62444. return engine.getCaps().drawBuffersExtension;
  62445. },
  62446. enumerable: true,
  62447. configurable: true
  62448. });
  62449. // Public Methods
  62450. /**
  62451. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  62452. */
  62453. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  62454. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  62455. for (var i = 0; i < this._scene.cameras.length; i++) {
  62456. var camera = this._scene.cameras[i];
  62457. this._originalColorPostProcess.dispose(camera);
  62458. this._ssaoPostProcess.dispose(camera);
  62459. this._blurHPostProcess.dispose(camera);
  62460. this._blurVPostProcess.dispose(camera);
  62461. this._ssaoCombinePostProcess.dispose(camera);
  62462. }
  62463. this._randomTexture.dispose();
  62464. if (disableGeometryBufferRenderer)
  62465. this._scene.disableGeometryBufferRenderer();
  62466. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  62467. _super.prototype.dispose.call(this);
  62468. };
  62469. // Private Methods
  62470. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  62471. var _this = this;
  62472. this._samplerOffsets = [];
  62473. var expensive = this.expensiveBlur;
  62474. for (var i = -8; i < 8; i++) {
  62475. this._samplerOffsets.push(i * 2 + 0.5);
  62476. }
  62477. 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");
  62478. this._blurHPostProcess.onApply = function (effect) {
  62479. if (!_this._scene.activeCamera) {
  62480. return;
  62481. }
  62482. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  62483. effect.setFloat("near", _this._scene.activeCamera.minZ);
  62484. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  62485. effect.setFloat("radius", _this.radius);
  62486. effect.setTexture("depthSampler", _this._depthTexture);
  62487. if (_this._firstUpdate) {
  62488. effect.setArray("samplerOffsets", _this._samplerOffsets);
  62489. }
  62490. };
  62491. 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");
  62492. this._blurVPostProcess.onApply = function (effect) {
  62493. if (!_this._scene.activeCamera) {
  62494. return;
  62495. }
  62496. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  62497. effect.setFloat("near", _this._scene.activeCamera.minZ);
  62498. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  62499. effect.setFloat("radius", _this.radius);
  62500. effect.setTexture("depthSampler", _this._depthTexture);
  62501. if (_this._firstUpdate) {
  62502. effect.setArray("samplerOffsets", _this._samplerOffsets);
  62503. _this._firstUpdate = false;
  62504. }
  62505. };
  62506. };
  62507. SSAO2RenderingPipeline.prototype._rebuild = function () {
  62508. this._firstUpdate = true;
  62509. _super.prototype._rebuild.call(this);
  62510. };
  62511. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  62512. var numSamples = this.samples;
  62513. var result = [];
  62514. var vector, scale;
  62515. var rand = function (min, max) {
  62516. return Math.random() * (max - min) + min;
  62517. };
  62518. var i = 0;
  62519. while (i < numSamples) {
  62520. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  62521. vector.normalize();
  62522. scale = i / numSamples;
  62523. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  62524. vector.scaleInPlace(scale);
  62525. result.push(vector.x, vector.y, vector.z);
  62526. i++;
  62527. }
  62528. return result;
  62529. };
  62530. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  62531. var _this = this;
  62532. var numSamples = this.samples;
  62533. this._sampleSphere = this._generateHemisphere();
  62534. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  62535. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  62536. "base", "range", "projection", "near", "far", "texelSize",
  62537. "xViewport", "yViewport", "maxZ", "minZAspect"
  62538. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  62539. this._ssaoPostProcess.onApply = function (effect) {
  62540. if (_this._firstUpdate) {
  62541. effect.setArray3("sampleSphere", _this._sampleSphere);
  62542. effect.setFloat("randTextureTiles", 4.0);
  62543. }
  62544. if (!_this._scene.activeCamera) {
  62545. return;
  62546. }
  62547. effect.setFloat("samplesFactor", 1 / _this.samples);
  62548. effect.setFloat("totalStrength", _this.totalStrength);
  62549. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  62550. effect.setFloat("radius", _this.radius);
  62551. effect.setFloat("maxZ", _this.maxZ);
  62552. effect.setFloat("minZAspect", _this.minZAspect);
  62553. effect.setFloat("base", _this.base);
  62554. effect.setFloat("near", _this._scene.activeCamera.minZ);
  62555. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  62556. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  62557. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  62558. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  62559. effect.setTexture("textureSampler", _this._depthTexture);
  62560. effect.setTexture("normalSampler", _this._normalTexture);
  62561. effect.setTexture("randomSampler", _this._randomTexture);
  62562. };
  62563. };
  62564. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  62565. var _this = this;
  62566. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  62567. this._ssaoCombinePostProcess.onApply = function (effect) {
  62568. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  62569. };
  62570. };
  62571. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  62572. var size = 512;
  62573. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  62574. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  62575. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  62576. var context = this._randomTexture.getContext();
  62577. var rand = function (min, max) {
  62578. return Math.random() * (max - min) + min;
  62579. };
  62580. var randVector = BABYLON.Vector3.Zero();
  62581. for (var x = 0; x < size; x++) {
  62582. for (var y = 0; y < size; y++) {
  62583. randVector.x = rand(0.0, 1.0);
  62584. randVector.y = rand(0.0, 1.0);
  62585. randVector.z = 0.0;
  62586. randVector.normalize();
  62587. randVector.scaleInPlace(255);
  62588. randVector.x = Math.floor(randVector.x);
  62589. randVector.y = Math.floor(randVector.y);
  62590. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  62591. context.fillRect(x, y, 1, 1);
  62592. }
  62593. }
  62594. this._randomTexture.update(false);
  62595. };
  62596. __decorate([
  62597. BABYLON.serialize()
  62598. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  62599. __decorate([
  62600. BABYLON.serialize()
  62601. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  62602. __decorate([
  62603. BABYLON.serialize()
  62604. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  62605. __decorate([
  62606. BABYLON.serialize("samples")
  62607. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  62608. __decorate([
  62609. BABYLON.serialize("expensiveBlur")
  62610. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  62611. __decorate([
  62612. BABYLON.serialize()
  62613. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  62614. __decorate([
  62615. BABYLON.serialize()
  62616. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  62617. return SSAO2RenderingPipeline;
  62618. }(BABYLON.PostProcessRenderPipeline));
  62619. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  62620. })(BABYLON || (BABYLON = {}));
  62621. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  62622. // BABYLON.JS Chromatic Aberration GLSL Shader
  62623. // Author: Olivier Guyot
  62624. // Separates very slightly R, G and B colors on the edges of the screen
  62625. // Inspired by Francois Tarlier & Martins Upitis
  62626. var BABYLON;
  62627. (function (BABYLON) {
  62628. var LensRenderingPipeline = /** @class */ (function (_super) {
  62629. __extends(LensRenderingPipeline, _super);
  62630. /**
  62631. * @constructor
  62632. *
  62633. * Effect parameters are as follow:
  62634. * {
  62635. * chromatic_aberration: number; // from 0 to x (1 for realism)
  62636. * edge_blur: number; // from 0 to x (1 for realism)
  62637. * distortion: number; // from 0 to x (1 for realism)
  62638. * grain_amount: number; // from 0 to 1
  62639. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  62640. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  62641. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  62642. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  62643. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  62644. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  62645. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  62646. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  62647. * }
  62648. * Note: if an effect parameter is unset, effect is disabled
  62649. *
  62650. * @param {string} name - The rendering pipeline name
  62651. * @param {object} parameters - An object containing all parameters (see above)
  62652. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  62653. * @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)
  62654. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  62655. */
  62656. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  62657. if (ratio === void 0) { ratio = 1.0; }
  62658. var _this = _super.call(this, scene.getEngine(), name) || this;
  62659. // Lens effects can be of the following:
  62660. // - chromatic aberration (slight shift of RGB colors)
  62661. // - blur on the edge of the lens
  62662. // - lens distortion
  62663. // - depth-of-field blur & highlights enhancing
  62664. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  62665. // - grain effect (noise or custom texture)
  62666. // Two additional texture samplers are needed:
  62667. // - depth map (for depth-of-field)
  62668. // - grain texture
  62669. /**
  62670. * The chromatic aberration PostProcess id in the pipeline
  62671. * @type {string}
  62672. */
  62673. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  62674. /**
  62675. * The highlights enhancing PostProcess id in the pipeline
  62676. * @type {string}
  62677. */
  62678. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  62679. /**
  62680. * The depth-of-field PostProcess id in the pipeline
  62681. * @type {string}
  62682. */
  62683. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  62684. _this._scene = scene;
  62685. // Fetch texture samplers
  62686. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  62687. if (parameters.grain_texture) {
  62688. _this._grainTexture = parameters.grain_texture;
  62689. }
  62690. else {
  62691. _this._createGrainTexture();
  62692. }
  62693. // save parameters
  62694. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  62695. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  62696. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  62697. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  62698. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  62699. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  62700. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  62701. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  62702. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  62703. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  62704. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  62705. // Create effects
  62706. _this._createChromaticAberrationPostProcess(ratio);
  62707. _this._createHighlightsPostProcess(ratio);
  62708. _this._createDepthOfFieldPostProcess(ratio / 4);
  62709. // Set up pipeline
  62710. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  62711. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  62712. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  62713. if (_this._highlightsGain === -1) {
  62714. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  62715. }
  62716. // Finish
  62717. scene.postProcessRenderPipelineManager.addPipeline(_this);
  62718. if (cameras) {
  62719. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  62720. }
  62721. return _this;
  62722. }
  62723. // public methods (self explanatory)
  62724. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  62725. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  62726. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  62727. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  62728. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  62729. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  62730. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  62731. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  62732. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  62733. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  62734. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  62735. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  62736. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  62737. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  62738. };
  62739. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  62740. this._highlightsPostProcess.updateEffect();
  62741. };
  62742. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  62743. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  62744. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  62745. this._highlightsGain = amount;
  62746. };
  62747. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  62748. if (this._highlightsGain === -1) {
  62749. this._highlightsGain = 1.0;
  62750. }
  62751. this._highlightsThreshold = amount;
  62752. };
  62753. LensRenderingPipeline.prototype.disableHighlights = function () {
  62754. this._highlightsGain = -1;
  62755. };
  62756. /**
  62757. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  62758. */
  62759. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  62760. if (disableDepthRender === void 0) { disableDepthRender = false; }
  62761. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  62762. this._chromaticAberrationPostProcess = null;
  62763. this._highlightsPostProcess = null;
  62764. this._depthOfFieldPostProcess = null;
  62765. this._grainTexture.dispose();
  62766. if (disableDepthRender)
  62767. this._scene.disableDepthRenderer();
  62768. };
  62769. // colors shifting and distortion
  62770. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  62771. var _this = this;
  62772. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  62773. [], // samplers
  62774. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  62775. this._chromaticAberrationPostProcess.onApply = function (effect) {
  62776. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  62777. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  62778. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  62779. };
  62780. };
  62781. // highlights enhancing
  62782. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  62783. var _this = this;
  62784. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  62785. [], // samplers
  62786. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  62787. this._highlightsPostProcess.onApply = function (effect) {
  62788. effect.setFloat('gain', _this._highlightsGain);
  62789. effect.setFloat('threshold', _this._highlightsThreshold);
  62790. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  62791. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  62792. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  62793. };
  62794. };
  62795. // colors shifting and distortion
  62796. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  62797. var _this = this;
  62798. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  62799. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  62800. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  62801. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  62802. this._depthOfFieldPostProcess.onApply = function (effect) {
  62803. effect.setTexture("depthSampler", _this._depthTexture);
  62804. effect.setTexture("grainSampler", _this._grainTexture);
  62805. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  62806. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  62807. effect.setFloat('grain_amount', _this._grainAmount);
  62808. effect.setBool('blur_noise', _this._blurNoise);
  62809. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  62810. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  62811. effect.setFloat('distortion', _this._distortion);
  62812. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  62813. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  62814. effect.setFloat('aperture', _this._dofAperture);
  62815. effect.setFloat('darken', _this._dofDarken);
  62816. effect.setFloat('edge_blur', _this._edgeBlur);
  62817. effect.setBool('highlights', (_this._highlightsGain !== -1));
  62818. if (_this._scene.activeCamera) {
  62819. effect.setFloat('near', _this._scene.activeCamera.minZ);
  62820. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  62821. }
  62822. };
  62823. };
  62824. // creates a black and white random noise texture, 512x512
  62825. LensRenderingPipeline.prototype._createGrainTexture = function () {
  62826. var size = 512;
  62827. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  62828. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  62829. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  62830. var context = this._grainTexture.getContext();
  62831. var rand = function (min, max) {
  62832. return Math.random() * (max - min) + min;
  62833. };
  62834. var value;
  62835. for (var x = 0; x < size; x++) {
  62836. for (var y = 0; y < size; y++) {
  62837. value = Math.floor(rand(0.42, 0.58) * 255);
  62838. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  62839. context.fillRect(x, y, 1, 1);
  62840. }
  62841. }
  62842. this._grainTexture.update(false);
  62843. };
  62844. return LensRenderingPipeline;
  62845. }(BABYLON.PostProcessRenderPipeline));
  62846. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  62847. })(BABYLON || (BABYLON = {}));
  62848. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  62849. var BABYLON;
  62850. (function (BABYLON) {
  62851. var StandardRenderingPipeline = /** @class */ (function (_super) {
  62852. __extends(StandardRenderingPipeline, _super);
  62853. /**
  62854. * @constructor
  62855. * @param {string} name - The rendering pipeline name
  62856. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  62857. * @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)
  62858. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  62859. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  62860. */
  62861. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  62862. if (originalPostProcess === void 0) { originalPostProcess = null; }
  62863. var _this = _super.call(this, scene.getEngine(), name) || this;
  62864. _this.downSampleX4PostProcess = null;
  62865. _this.brightPassPostProcess = null;
  62866. _this.blurHPostProcesses = [];
  62867. _this.blurVPostProcesses = [];
  62868. _this.textureAdderPostProcess = null;
  62869. _this.volumetricLightPostProcess = null;
  62870. _this.volumetricLightSmoothXPostProcess = null;
  62871. _this.volumetricLightSmoothYPostProcess = null;
  62872. _this.volumetricLightMergePostProces = null;
  62873. _this.volumetricLightFinalPostProcess = null;
  62874. _this.luminancePostProcess = null;
  62875. _this.luminanceDownSamplePostProcesses = [];
  62876. _this.hdrPostProcess = null;
  62877. _this.textureAdderFinalPostProcess = null;
  62878. _this.lensFlareFinalPostProcess = null;
  62879. _this.hdrFinalPostProcess = null;
  62880. _this.lensFlarePostProcess = null;
  62881. _this.lensFlareComposePostProcess = null;
  62882. _this.motionBlurPostProcess = null;
  62883. _this.depthOfFieldPostProcess = null;
  62884. // Values
  62885. _this.brightThreshold = 1.0;
  62886. _this.blurWidth = 512.0;
  62887. _this.horizontalBlur = false;
  62888. _this.exposure = 1.0;
  62889. _this.lensTexture = null;
  62890. _this.volumetricLightCoefficient = 0.2;
  62891. _this.volumetricLightPower = 4.0;
  62892. _this.volumetricLightBlurScale = 64.0;
  62893. _this.sourceLight = null;
  62894. _this.hdrMinimumLuminance = 1.0;
  62895. _this.hdrDecreaseRate = 0.5;
  62896. _this.hdrIncreaseRate = 0.5;
  62897. _this.lensColorTexture = null;
  62898. _this.lensFlareStrength = 20.0;
  62899. _this.lensFlareGhostDispersal = 1.4;
  62900. _this.lensFlareHaloWidth = 0.7;
  62901. _this.lensFlareDistortionStrength = 16.0;
  62902. _this.lensStarTexture = null;
  62903. _this.lensFlareDirtTexture = null;
  62904. _this.depthOfFieldDistance = 10.0;
  62905. _this.depthOfFieldBlurWidth = 64.0;
  62906. _this.motionStrength = 1.0;
  62907. // IAnimatable
  62908. _this.animations = [];
  62909. _this._currentDepthOfFieldSource = null;
  62910. _this._hdrCurrentLuminance = 1.0;
  62911. // Getters and setters
  62912. _this._bloomEnabled = true;
  62913. _this._depthOfFieldEnabled = false;
  62914. _this._vlsEnabled = false;
  62915. _this._lensFlareEnabled = false;
  62916. _this._hdrEnabled = false;
  62917. _this._motionBlurEnabled = false;
  62918. _this._motionBlurSamples = 64.0;
  62919. _this._volumetricLightStepsCount = 50.0;
  62920. _this._cameras = cameras || [];
  62921. // Initialize
  62922. _this._scene = scene;
  62923. _this._basePostProcess = originalPostProcess;
  62924. _this._ratio = ratio;
  62925. // Misc
  62926. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  62927. // Finish
  62928. scene.postProcessRenderPipelineManager.addPipeline(_this);
  62929. _this._buildPipeline();
  62930. return _this;
  62931. }
  62932. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  62933. get: function () {
  62934. return this._bloomEnabled;
  62935. },
  62936. set: function (enabled) {
  62937. if (this._bloomEnabled === enabled) {
  62938. return;
  62939. }
  62940. this._bloomEnabled = enabled;
  62941. this._buildPipeline();
  62942. },
  62943. enumerable: true,
  62944. configurable: true
  62945. });
  62946. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  62947. get: function () {
  62948. return this._depthOfFieldEnabled;
  62949. },
  62950. set: function (enabled) {
  62951. if (this._depthOfFieldEnabled === enabled) {
  62952. return;
  62953. }
  62954. this._depthOfFieldEnabled = enabled;
  62955. this._buildPipeline();
  62956. },
  62957. enumerable: true,
  62958. configurable: true
  62959. });
  62960. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  62961. get: function () {
  62962. return this._lensFlareEnabled;
  62963. },
  62964. set: function (enabled) {
  62965. if (this._lensFlareEnabled === enabled) {
  62966. return;
  62967. }
  62968. this._lensFlareEnabled = enabled;
  62969. this._buildPipeline();
  62970. },
  62971. enumerable: true,
  62972. configurable: true
  62973. });
  62974. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  62975. get: function () {
  62976. return this._hdrEnabled;
  62977. },
  62978. set: function (enabled) {
  62979. if (this._hdrEnabled === enabled) {
  62980. return;
  62981. }
  62982. this._hdrEnabled = enabled;
  62983. this._buildPipeline();
  62984. },
  62985. enumerable: true,
  62986. configurable: true
  62987. });
  62988. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  62989. get: function () {
  62990. return this._vlsEnabled;
  62991. },
  62992. set: function (enabled) {
  62993. if (this._vlsEnabled === enabled) {
  62994. return;
  62995. }
  62996. if (enabled) {
  62997. var geometry = this._scene.enableGeometryBufferRenderer();
  62998. if (!geometry) {
  62999. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  63000. return;
  63001. }
  63002. }
  63003. this._vlsEnabled = enabled;
  63004. this._buildPipeline();
  63005. },
  63006. enumerable: true,
  63007. configurable: true
  63008. });
  63009. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  63010. get: function () {
  63011. return this._motionBlurEnabled;
  63012. },
  63013. set: function (enabled) {
  63014. if (this._motionBlurEnabled === enabled) {
  63015. return;
  63016. }
  63017. this._motionBlurEnabled = enabled;
  63018. this._buildPipeline();
  63019. },
  63020. enumerable: true,
  63021. configurable: true
  63022. });
  63023. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  63024. get: function () {
  63025. return this._volumetricLightStepsCount;
  63026. },
  63027. set: function (count) {
  63028. if (this.volumetricLightPostProcess) {
  63029. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  63030. }
  63031. this._volumetricLightStepsCount = count;
  63032. },
  63033. enumerable: true,
  63034. configurable: true
  63035. });
  63036. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  63037. get: function () {
  63038. return this._motionBlurSamples;
  63039. },
  63040. set: function (samples) {
  63041. if (this.motionBlurPostProcess) {
  63042. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  63043. }
  63044. this._motionBlurSamples = samples;
  63045. },
  63046. enumerable: true,
  63047. configurable: true
  63048. });
  63049. StandardRenderingPipeline.prototype._buildPipeline = function () {
  63050. var _this = this;
  63051. var ratio = this._ratio;
  63052. var scene = this._scene;
  63053. this._disposePostProcesses();
  63054. this._reset();
  63055. // Create pass post-process
  63056. if (!this._basePostProcess) {
  63057. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  63058. this.originalPostProcess.onApply = function (effect) {
  63059. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  63060. };
  63061. }
  63062. else {
  63063. this.originalPostProcess = this._basePostProcess;
  63064. }
  63065. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  63066. this._currentDepthOfFieldSource = this.originalPostProcess;
  63067. if (this._vlsEnabled) {
  63068. // Create volumetric light
  63069. this._createVolumetricLightPostProcess(scene, ratio);
  63070. // Create volumetric light final post-process
  63071. 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);
  63072. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  63073. }
  63074. if (this._bloomEnabled) {
  63075. // Create down sample X4 post-process
  63076. this._createDownSampleX4PostProcess(scene, ratio / 2);
  63077. // Create bright pass post-process
  63078. this._createBrightPassPostProcess(scene, ratio / 2);
  63079. // Create gaussian blur post-processes (down sampling blurs)
  63080. this._createBlurPostProcesses(scene, ratio / 4, 1);
  63081. // Create texture adder post-process
  63082. this._createTextureAdderPostProcess(scene, ratio);
  63083. // Create depth-of-field source post-process
  63084. 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);
  63085. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  63086. }
  63087. if (this._lensFlareEnabled) {
  63088. // Create lens flare post-process
  63089. this._createLensFlarePostProcess(scene, ratio);
  63090. // Create depth-of-field source post-process post lens-flare and disable it now
  63091. 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);
  63092. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  63093. }
  63094. if (this._hdrEnabled) {
  63095. // Create luminance
  63096. this._createLuminancePostProcesses(scene, this._floatTextureType);
  63097. // Create HDR
  63098. this._createHdrPostProcess(scene, ratio);
  63099. // Create depth-of-field source post-process post hdr and disable it now
  63100. 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);
  63101. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  63102. }
  63103. if (this._depthOfFieldEnabled) {
  63104. // Create gaussian blur used by depth-of-field
  63105. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  63106. // Create depth-of-field post-process
  63107. this._createDepthOfFieldPostProcess(scene, ratio);
  63108. }
  63109. if (this._motionBlurEnabled) {
  63110. // Create motion blur post-process
  63111. this._createMotionBlurPostProcess(scene, ratio);
  63112. }
  63113. if (this._cameras !== null) {
  63114. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  63115. }
  63116. };
  63117. // Down Sample X4 Post-Processs
  63118. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  63119. var _this = this;
  63120. var downSampleX4Offsets = new Array(32);
  63121. 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);
  63122. this.downSampleX4PostProcess.onApply = function (effect) {
  63123. var id = 0;
  63124. var width = _this.downSampleX4PostProcess.width;
  63125. var height = _this.downSampleX4PostProcess.height;
  63126. for (var i = -2; i < 2; i++) {
  63127. for (var j = -2; j < 2; j++) {
  63128. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  63129. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  63130. id += 2;
  63131. }
  63132. }
  63133. effect.setArray2("dsOffsets", downSampleX4Offsets);
  63134. };
  63135. // Add to pipeline
  63136. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  63137. };
  63138. // Brightpass Post-Process
  63139. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  63140. var _this = this;
  63141. var brightOffsets = new Array(8);
  63142. 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);
  63143. this.brightPassPostProcess.onApply = function (effect) {
  63144. var sU = (1.0 / _this.brightPassPostProcess.width);
  63145. var sV = (1.0 / _this.brightPassPostProcess.height);
  63146. brightOffsets[0] = -0.5 * sU;
  63147. brightOffsets[1] = 0.5 * sV;
  63148. brightOffsets[2] = 0.5 * sU;
  63149. brightOffsets[3] = 0.5 * sV;
  63150. brightOffsets[4] = -0.5 * sU;
  63151. brightOffsets[5] = -0.5 * sV;
  63152. brightOffsets[6] = 0.5 * sU;
  63153. brightOffsets[7] = -0.5 * sV;
  63154. effect.setArray2("dsOffsets", brightOffsets);
  63155. effect.setFloat("brightThreshold", _this.brightThreshold);
  63156. };
  63157. // Add to pipeline
  63158. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  63159. };
  63160. // Create blur H&V post-processes
  63161. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  63162. var _this = this;
  63163. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  63164. var engine = scene.getEngine();
  63165. 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);
  63166. 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);
  63167. blurX.onActivateObservable.add(function () {
  63168. var dw = blurX.width / engine.getRenderWidth();
  63169. blurX.kernel = _this[blurWidthKey] * dw;
  63170. });
  63171. blurY.onActivateObservable.add(function () {
  63172. var dw = blurY.height / engine.getRenderHeight();
  63173. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  63174. });
  63175. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  63176. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  63177. this.blurHPostProcesses.push(blurX);
  63178. this.blurVPostProcesses.push(blurY);
  63179. };
  63180. // Create texture adder post-process
  63181. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  63182. var _this = this;
  63183. 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);
  63184. this.textureAdderPostProcess.onApply = function (effect) {
  63185. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  63186. effect.setTexture("lensSampler", _this.lensTexture);
  63187. effect.setFloat("exposure", _this.exposure);
  63188. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  63189. };
  63190. // Add to pipeline
  63191. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  63192. };
  63193. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  63194. var _this = this;
  63195. var geometryRenderer = scene.enableGeometryBufferRenderer();
  63196. geometryRenderer.enablePosition = true;
  63197. var geometry = geometryRenderer.getGBuffer();
  63198. // Base post-process
  63199. 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));
  63200. var depthValues = BABYLON.Vector2.Zero();
  63201. this.volumetricLightPostProcess.onApply = function (effect) {
  63202. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  63203. var generator = _this.sourceLight.getShadowGenerator();
  63204. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  63205. effect.setTexture("positionSampler", geometry.textures[2]);
  63206. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  63207. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  63208. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  63209. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  63210. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  63211. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  63212. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  63213. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  63214. effect.setVector2("depthValues", depthValues);
  63215. }
  63216. };
  63217. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  63218. // Smooth
  63219. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  63220. // Merge
  63221. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  63222. this.volumetricLightMergePostProces.onApply = function (effect) {
  63223. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  63224. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  63225. };
  63226. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  63227. };
  63228. // Create luminance
  63229. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  63230. var _this = this;
  63231. // Create luminance
  63232. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  63233. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  63234. var offsets = [];
  63235. this.luminancePostProcess.onApply = function (effect) {
  63236. var sU = (1.0 / _this.luminancePostProcess.width);
  63237. var sV = (1.0 / _this.luminancePostProcess.height);
  63238. offsets[0] = -0.5 * sU;
  63239. offsets[1] = 0.5 * sV;
  63240. offsets[2] = 0.5 * sU;
  63241. offsets[3] = 0.5 * sV;
  63242. offsets[4] = -0.5 * sU;
  63243. offsets[5] = -0.5 * sV;
  63244. offsets[6] = 0.5 * sU;
  63245. offsets[7] = -0.5 * sV;
  63246. effect.setArray2("lumOffsets", offsets);
  63247. };
  63248. // Add to pipeline
  63249. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  63250. // Create down sample luminance
  63251. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  63252. var size = Math.pow(3, i);
  63253. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  63254. if (i === 0) {
  63255. defines += "#define FINAL_DOWN_SAMPLER";
  63256. }
  63257. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  63258. this.luminanceDownSamplePostProcesses.push(postProcess);
  63259. }
  63260. // Create callbacks and add effects
  63261. var lastLuminance = this.luminancePostProcess;
  63262. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  63263. var downSampleOffsets = new Array(18);
  63264. pp.onApply = function (effect) {
  63265. if (!lastLuminance) {
  63266. return;
  63267. }
  63268. var id = 0;
  63269. for (var x = -1; x < 2; x++) {
  63270. for (var y = -1; y < 2; y++) {
  63271. downSampleOffsets[id] = x / lastLuminance.width;
  63272. downSampleOffsets[id + 1] = y / lastLuminance.height;
  63273. id += 2;
  63274. }
  63275. }
  63276. effect.setArray2("dsOffsets", downSampleOffsets);
  63277. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  63278. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  63279. lastLuminance = _this.luminancePostProcess;
  63280. }
  63281. else {
  63282. lastLuminance = pp;
  63283. }
  63284. };
  63285. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  63286. pp.onAfterRender = function (effect) {
  63287. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  63288. 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);
  63289. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  63290. };
  63291. }
  63292. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  63293. });
  63294. };
  63295. // Create HDR post-process
  63296. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  63297. var _this = this;
  63298. 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);
  63299. var outputLiminance = 1;
  63300. var time = 0;
  63301. var lastTime = 0;
  63302. this.hdrPostProcess.onApply = function (effect) {
  63303. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  63304. time += scene.getEngine().getDeltaTime();
  63305. if (outputLiminance < 0) {
  63306. outputLiminance = _this._hdrCurrentLuminance;
  63307. }
  63308. else {
  63309. var dt = (lastTime - time) / 1000.0;
  63310. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  63311. outputLiminance += _this.hdrDecreaseRate * dt;
  63312. }
  63313. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  63314. outputLiminance -= _this.hdrIncreaseRate * dt;
  63315. }
  63316. else {
  63317. outputLiminance = _this._hdrCurrentLuminance;
  63318. }
  63319. }
  63320. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  63321. effect.setFloat("averageLuminance", outputLiminance);
  63322. lastTime = time;
  63323. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  63324. };
  63325. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  63326. };
  63327. // Create lens flare post-process
  63328. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  63329. var _this = this;
  63330. 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);
  63331. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  63332. this._createBlurPostProcesses(scene, ratio / 4, 2);
  63333. 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);
  63334. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  63335. var resolution = new BABYLON.Vector2(0, 0);
  63336. // Lens flare
  63337. this.lensFlarePostProcess.onApply = function (effect) {
  63338. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  63339. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  63340. effect.setFloat("strength", _this.lensFlareStrength);
  63341. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  63342. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  63343. // Shift
  63344. resolution.x = _this.lensFlarePostProcess.width;
  63345. resolution.y = _this.lensFlarePostProcess.height;
  63346. effect.setVector2("resolution", resolution);
  63347. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  63348. };
  63349. // Compose
  63350. 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);
  63351. 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);
  63352. this.lensFlareComposePostProcess.onApply = function (effect) {
  63353. if (!_this._scene.activeCamera) {
  63354. return;
  63355. }
  63356. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  63357. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  63358. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  63359. // Lens start rotation matrix
  63360. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  63361. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  63362. 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));
  63363. camRot *= 4.0;
  63364. 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);
  63365. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  63366. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  63367. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  63368. };
  63369. };
  63370. // Create depth-of-field post-process
  63371. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  63372. var _this = this;
  63373. 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);
  63374. this.depthOfFieldPostProcess.onApply = function (effect) {
  63375. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  63376. effect.setTexture("depthSampler", _this._getDepthTexture());
  63377. effect.setFloat("distance", _this.depthOfFieldDistance);
  63378. };
  63379. // Add to pipeline
  63380. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  63381. };
  63382. // Create motion blur post-process
  63383. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  63384. var _this = this;
  63385. 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);
  63386. var motionScale = 0;
  63387. var prevViewProjection = BABYLON.Matrix.Identity();
  63388. var invViewProjection = BABYLON.Matrix.Identity();
  63389. var viewProjection = BABYLON.Matrix.Identity();
  63390. var screenSize = BABYLON.Vector2.Zero();
  63391. this.motionBlurPostProcess.onApply = function (effect) {
  63392. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  63393. viewProjection.invertToRef(invViewProjection);
  63394. effect.setMatrix("inverseViewProjection", invViewProjection);
  63395. effect.setMatrix("prevViewProjection", prevViewProjection);
  63396. prevViewProjection = viewProjection;
  63397. screenSize.x = _this.motionBlurPostProcess.width;
  63398. screenSize.y = _this.motionBlurPostProcess.height;
  63399. effect.setVector2("screenSize", screenSize);
  63400. motionScale = scene.getEngine().getFps() / 60.0;
  63401. effect.setFloat("motionScale", motionScale);
  63402. effect.setFloat("motionStrength", _this.motionStrength);
  63403. effect.setTexture("depthSampler", _this._getDepthTexture());
  63404. };
  63405. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  63406. };
  63407. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  63408. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  63409. var renderer = this._scene.enableGeometryBufferRenderer();
  63410. return renderer.getGBuffer().textures[0];
  63411. }
  63412. return this._scene.enableDepthRenderer().getDepthMap();
  63413. };
  63414. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  63415. for (var i = 0; i < this._cameras.length; i++) {
  63416. var camera = this._cameras[i];
  63417. if (this.originalPostProcess) {
  63418. this.originalPostProcess.dispose(camera);
  63419. }
  63420. if (this.downSampleX4PostProcess) {
  63421. this.downSampleX4PostProcess.dispose(camera);
  63422. }
  63423. if (this.brightPassPostProcess) {
  63424. this.brightPassPostProcess.dispose(camera);
  63425. }
  63426. if (this.textureAdderPostProcess) {
  63427. this.textureAdderPostProcess.dispose(camera);
  63428. }
  63429. if (this.textureAdderFinalPostProcess) {
  63430. this.textureAdderFinalPostProcess.dispose(camera);
  63431. }
  63432. if (this.volumetricLightPostProcess) {
  63433. this.volumetricLightPostProcess.dispose(camera);
  63434. }
  63435. if (this.volumetricLightSmoothXPostProcess) {
  63436. this.volumetricLightSmoothXPostProcess.dispose(camera);
  63437. }
  63438. if (this.volumetricLightSmoothYPostProcess) {
  63439. this.volumetricLightSmoothYPostProcess.dispose(camera);
  63440. }
  63441. if (this.volumetricLightMergePostProces) {
  63442. this.volumetricLightMergePostProces.dispose(camera);
  63443. }
  63444. if (this.volumetricLightFinalPostProcess) {
  63445. this.volumetricLightFinalPostProcess.dispose(camera);
  63446. }
  63447. if (this.lensFlarePostProcess) {
  63448. this.lensFlarePostProcess.dispose(camera);
  63449. }
  63450. if (this.lensFlareComposePostProcess) {
  63451. this.lensFlareComposePostProcess.dispose(camera);
  63452. }
  63453. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  63454. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  63455. }
  63456. if (this.luminancePostProcess) {
  63457. this.luminancePostProcess.dispose(camera);
  63458. }
  63459. if (this.hdrPostProcess) {
  63460. this.hdrPostProcess.dispose(camera);
  63461. }
  63462. if (this.hdrFinalPostProcess) {
  63463. this.hdrFinalPostProcess.dispose(camera);
  63464. }
  63465. if (this.depthOfFieldPostProcess) {
  63466. this.depthOfFieldPostProcess.dispose(camera);
  63467. }
  63468. if (this.motionBlurPostProcess) {
  63469. this.motionBlurPostProcess.dispose(camera);
  63470. }
  63471. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  63472. this.blurHPostProcesses[j].dispose(camera);
  63473. }
  63474. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  63475. this.blurVPostProcesses[j].dispose(camera);
  63476. }
  63477. }
  63478. this.originalPostProcess = null;
  63479. this.downSampleX4PostProcess = null;
  63480. this.brightPassPostProcess = null;
  63481. this.textureAdderPostProcess = null;
  63482. this.textureAdderFinalPostProcess = null;
  63483. this.volumetricLightPostProcess = null;
  63484. this.volumetricLightSmoothXPostProcess = null;
  63485. this.volumetricLightSmoothYPostProcess = null;
  63486. this.volumetricLightMergePostProces = null;
  63487. this.volumetricLightFinalPostProcess = null;
  63488. this.lensFlarePostProcess = null;
  63489. this.lensFlareComposePostProcess = null;
  63490. this.luminancePostProcess = null;
  63491. this.hdrPostProcess = null;
  63492. this.hdrFinalPostProcess = null;
  63493. this.depthOfFieldPostProcess = null;
  63494. this.motionBlurPostProcess = null;
  63495. this.luminanceDownSamplePostProcesses = [];
  63496. this.blurHPostProcesses = [];
  63497. this.blurVPostProcesses = [];
  63498. };
  63499. // Dispose
  63500. StandardRenderingPipeline.prototype.dispose = function () {
  63501. this._disposePostProcesses();
  63502. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  63503. _super.prototype.dispose.call(this);
  63504. };
  63505. // Serialize rendering pipeline
  63506. StandardRenderingPipeline.prototype.serialize = function () {
  63507. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  63508. serializationObject.customType = "StandardRenderingPipeline";
  63509. return serializationObject;
  63510. };
  63511. /**
  63512. * Static members
  63513. */
  63514. // Parse serialized pipeline
  63515. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  63516. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  63517. };
  63518. // Luminance steps
  63519. StandardRenderingPipeline.LuminanceSteps = 6;
  63520. __decorate([
  63521. BABYLON.serialize()
  63522. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  63523. __decorate([
  63524. BABYLON.serialize()
  63525. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  63526. __decorate([
  63527. BABYLON.serialize()
  63528. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  63529. __decorate([
  63530. BABYLON.serialize()
  63531. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  63532. __decorate([
  63533. BABYLON.serializeAsTexture("lensTexture")
  63534. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  63535. __decorate([
  63536. BABYLON.serialize()
  63537. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  63538. __decorate([
  63539. BABYLON.serialize()
  63540. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  63541. __decorate([
  63542. BABYLON.serialize()
  63543. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  63544. __decorate([
  63545. BABYLON.serialize()
  63546. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  63547. __decorate([
  63548. BABYLON.serialize()
  63549. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  63550. __decorate([
  63551. BABYLON.serialize()
  63552. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  63553. __decorate([
  63554. BABYLON.serializeAsTexture("lensColorTexture")
  63555. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  63556. __decorate([
  63557. BABYLON.serialize()
  63558. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  63559. __decorate([
  63560. BABYLON.serialize()
  63561. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  63562. __decorate([
  63563. BABYLON.serialize()
  63564. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  63565. __decorate([
  63566. BABYLON.serialize()
  63567. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  63568. __decorate([
  63569. BABYLON.serializeAsTexture("lensStarTexture")
  63570. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  63571. __decorate([
  63572. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  63573. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  63574. __decorate([
  63575. BABYLON.serialize()
  63576. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  63577. __decorate([
  63578. BABYLON.serialize()
  63579. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  63580. __decorate([
  63581. BABYLON.serialize()
  63582. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  63583. __decorate([
  63584. BABYLON.serialize()
  63585. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  63586. __decorate([
  63587. BABYLON.serialize()
  63588. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  63589. __decorate([
  63590. BABYLON.serialize()
  63591. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  63592. __decorate([
  63593. BABYLON.serialize()
  63594. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  63595. __decorate([
  63596. BABYLON.serialize()
  63597. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  63598. __decorate([
  63599. BABYLON.serialize()
  63600. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  63601. __decorate([
  63602. BABYLON.serialize()
  63603. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  63604. __decorate([
  63605. BABYLON.serialize()
  63606. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  63607. __decorate([
  63608. BABYLON.serialize()
  63609. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  63610. return StandardRenderingPipeline;
  63611. }(BABYLON.PostProcessRenderPipeline));
  63612. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  63613. })(BABYLON || (BABYLON = {}));
  63614. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  63615. var BABYLON;
  63616. (function (BABYLON) {
  63617. var FxaaPostProcess = /** @class */ (function (_super) {
  63618. __extends(FxaaPostProcess, _super);
  63619. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  63620. if (camera === void 0) { camera = null; }
  63621. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63622. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  63623. _this.onApplyObservable.add(function (effect) {
  63624. var texelSize = _this.texelSize;
  63625. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  63626. });
  63627. return _this;
  63628. }
  63629. return FxaaPostProcess;
  63630. }(BABYLON.PostProcess));
  63631. BABYLON.FxaaPostProcess = FxaaPostProcess;
  63632. })(BABYLON || (BABYLON = {}));
  63633. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  63634. var BABYLON;
  63635. (function (BABYLON) {
  63636. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  63637. __extends(DefaultRenderingPipeline, _super);
  63638. /**
  63639. * @constructor
  63640. * @param {string} name - The rendering pipeline name
  63641. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  63642. * @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)
  63643. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  63644. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  63645. */
  63646. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  63647. if (automaticBuild === void 0) { automaticBuild = true; }
  63648. var _this = _super.call(this, scene.getEngine(), name) || this;
  63649. _this.PassPostProcessId = "PassPostProcessEffect";
  63650. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  63651. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  63652. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  63653. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  63654. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  63655. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  63656. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  63657. // IAnimatable
  63658. _this.animations = [];
  63659. // Values
  63660. _this._bloomEnabled = false;
  63661. _this._fxaaEnabled = false;
  63662. _this._imageProcessingEnabled = true;
  63663. _this._bloomScale = 0.6;
  63664. _this._buildAllowed = true;
  63665. /**
  63666. * Specifies the size of the bloom blur kernel, relative to the final output size
  63667. */
  63668. _this.bloomKernel = 64;
  63669. /**
  63670. * Specifies the weight of the bloom in the final rendering
  63671. */
  63672. _this._bloomWeight = 0.15;
  63673. _this._cameras = cameras || [];
  63674. _this._buildAllowed = automaticBuild;
  63675. // Initialize
  63676. _this._scene = scene;
  63677. var caps = _this._scene.getEngine().getCaps();
  63678. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  63679. // Misc
  63680. if (_this._hdr) {
  63681. if (caps.textureHalfFloatRender) {
  63682. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  63683. }
  63684. else if (caps.textureFloatRender) {
  63685. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  63686. }
  63687. }
  63688. else {
  63689. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  63690. }
  63691. // Attach
  63692. scene.postProcessRenderPipelineManager.addPipeline(_this);
  63693. _this._buildPipeline();
  63694. return _this;
  63695. }
  63696. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  63697. get: function () {
  63698. return this._bloomWeight;
  63699. },
  63700. set: function (value) {
  63701. if (this._bloomWeight === value) {
  63702. return;
  63703. }
  63704. this._bloomWeight = value;
  63705. if (this._hdr && this.copyBack) {
  63706. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  63707. }
  63708. },
  63709. enumerable: true,
  63710. configurable: true
  63711. });
  63712. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  63713. get: function () {
  63714. return this._bloomScale;
  63715. },
  63716. set: function (value) {
  63717. if (this._bloomScale === value) {
  63718. return;
  63719. }
  63720. this._bloomScale = value;
  63721. this._buildPipeline();
  63722. },
  63723. enumerable: true,
  63724. configurable: true
  63725. });
  63726. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  63727. get: function () {
  63728. return this._bloomEnabled;
  63729. },
  63730. set: function (enabled) {
  63731. if (this._bloomEnabled === enabled) {
  63732. return;
  63733. }
  63734. this._bloomEnabled = enabled;
  63735. this._buildPipeline();
  63736. },
  63737. enumerable: true,
  63738. configurable: true
  63739. });
  63740. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  63741. get: function () {
  63742. return this._fxaaEnabled;
  63743. },
  63744. set: function (enabled) {
  63745. if (this._fxaaEnabled === enabled) {
  63746. return;
  63747. }
  63748. this._fxaaEnabled = enabled;
  63749. this._buildPipeline();
  63750. },
  63751. enumerable: true,
  63752. configurable: true
  63753. });
  63754. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  63755. get: function () {
  63756. return this._imageProcessingEnabled;
  63757. },
  63758. set: function (enabled) {
  63759. if (this._imageProcessingEnabled === enabled) {
  63760. return;
  63761. }
  63762. this._imageProcessingEnabled = enabled;
  63763. this._buildPipeline();
  63764. },
  63765. enumerable: true,
  63766. configurable: true
  63767. });
  63768. /**
  63769. * Force the compilation of the entire pipeline.
  63770. */
  63771. DefaultRenderingPipeline.prototype.prepare = function () {
  63772. var previousState = this._buildAllowed;
  63773. this._buildAllowed = true;
  63774. this._buildPipeline();
  63775. this._buildAllowed = previousState;
  63776. };
  63777. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  63778. var _this = this;
  63779. if (!this._buildAllowed) {
  63780. return;
  63781. }
  63782. var engine = this._scene.getEngine();
  63783. this._disposePostProcesses();
  63784. this._reset();
  63785. if (this.bloomEnabled) {
  63786. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  63787. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  63788. if (!this._hdr) {
  63789. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  63790. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  63791. this.highlights.autoClear = false;
  63792. this.highlights.alwaysForcePOT = true;
  63793. }
  63794. 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);
  63795. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  63796. this.blurX.alwaysForcePOT = true;
  63797. this.blurX.autoClear = false;
  63798. this.blurX.onActivateObservable.add(function () {
  63799. var dw = _this.blurX.width / engine.getRenderWidth(true);
  63800. _this.blurX.kernel = _this.bloomKernel * dw;
  63801. });
  63802. 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);
  63803. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  63804. this.blurY.alwaysForcePOT = true;
  63805. this.blurY.autoClear = false;
  63806. this.blurY.onActivateObservable.add(function () {
  63807. var dh = _this.blurY.height / engine.getRenderHeight(true);
  63808. _this.blurY.kernel = _this.bloomKernel * dh;
  63809. });
  63810. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  63811. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  63812. this.copyBack.alwaysForcePOT = true;
  63813. if (this._hdr) {
  63814. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  63815. var w = this.bloomWeight;
  63816. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  63817. }
  63818. else {
  63819. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  63820. }
  63821. this.copyBack.autoClear = false;
  63822. }
  63823. if (this._imageProcessingEnabled) {
  63824. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  63825. if (this._hdr) {
  63826. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  63827. }
  63828. else {
  63829. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  63830. }
  63831. }
  63832. if (this.fxaaEnabled) {
  63833. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  63834. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  63835. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  63836. }
  63837. else if (this._hdr && this.imageProcessing) {
  63838. this.finalMerge = this.imageProcessing;
  63839. }
  63840. else {
  63841. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  63842. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  63843. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  63844. }
  63845. if (this.bloomEnabled) {
  63846. if (this._hdr) {
  63847. this.copyBack.shareOutputWith(this.blurX);
  63848. if (this.imageProcessing) {
  63849. this.imageProcessing.shareOutputWith(this.pass);
  63850. this.imageProcessing.autoClear = false;
  63851. }
  63852. else if (this.fxaa) {
  63853. this.fxaa.shareOutputWith(this.pass);
  63854. }
  63855. else {
  63856. this.finalMerge.shareOutputWith(this.pass);
  63857. }
  63858. }
  63859. else {
  63860. if (this.fxaa) {
  63861. this.fxaa.shareOutputWith(this.pass);
  63862. }
  63863. else {
  63864. this.finalMerge.shareOutputWith(this.pass);
  63865. }
  63866. }
  63867. }
  63868. if (this._cameras !== null) {
  63869. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  63870. }
  63871. };
  63872. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  63873. for (var i = 0; i < this._cameras.length; i++) {
  63874. var camera = this._cameras[i];
  63875. if (this.pass) {
  63876. this.pass.dispose(camera);
  63877. }
  63878. if (this.highlights) {
  63879. this.highlights.dispose(camera);
  63880. }
  63881. if (this.blurX) {
  63882. this.blurX.dispose(camera);
  63883. }
  63884. if (this.blurY) {
  63885. this.blurY.dispose(camera);
  63886. }
  63887. if (this.copyBack) {
  63888. this.copyBack.dispose(camera);
  63889. }
  63890. if (this.imageProcessing) {
  63891. this.imageProcessing.dispose(camera);
  63892. }
  63893. if (this.fxaa) {
  63894. this.fxaa.dispose(camera);
  63895. }
  63896. if (this.finalMerge) {
  63897. this.finalMerge.dispose(camera);
  63898. }
  63899. }
  63900. this.pass = null;
  63901. this.highlights = null;
  63902. this.blurX = null;
  63903. this.blurY = null;
  63904. this.copyBack = null;
  63905. this.imageProcessing = null;
  63906. this.fxaa = null;
  63907. this.finalMerge = null;
  63908. };
  63909. // Dispose
  63910. DefaultRenderingPipeline.prototype.dispose = function () {
  63911. this._disposePostProcesses();
  63912. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  63913. _super.prototype.dispose.call(this);
  63914. };
  63915. // Serialize rendering pipeline
  63916. DefaultRenderingPipeline.prototype.serialize = function () {
  63917. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  63918. serializationObject.customType = "DefaultRenderingPipeline";
  63919. return serializationObject;
  63920. };
  63921. // Parse serialized pipeline
  63922. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  63923. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  63924. };
  63925. __decorate([
  63926. BABYLON.serialize()
  63927. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  63928. __decorate([
  63929. BABYLON.serialize()
  63930. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  63931. __decorate([
  63932. BABYLON.serialize()
  63933. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  63934. __decorate([
  63935. BABYLON.serialize()
  63936. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  63937. __decorate([
  63938. BABYLON.serialize()
  63939. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  63940. __decorate([
  63941. BABYLON.serialize()
  63942. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  63943. __decorate([
  63944. BABYLON.serialize()
  63945. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  63946. __decorate([
  63947. BABYLON.serialize()
  63948. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  63949. return DefaultRenderingPipeline;
  63950. }(BABYLON.PostProcessRenderPipeline));
  63951. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  63952. })(BABYLON || (BABYLON = {}));
  63953. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  63954. var BABYLON;
  63955. (function (BABYLON) {
  63956. /**
  63957. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  63958. */
  63959. var GeometryBufferRenderer = /** @class */ (function () {
  63960. /**
  63961. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  63962. * @param scene The scene the buffer belongs to
  63963. * @param ratio How big is the buffer related to the main canvas.
  63964. */
  63965. function GeometryBufferRenderer(scene, ratio) {
  63966. if (ratio === void 0) { ratio = 1; }
  63967. this._enablePosition = false;
  63968. this._scene = scene;
  63969. this._ratio = ratio;
  63970. // Render target
  63971. this._createRenderTargets();
  63972. }
  63973. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  63974. /**
  63975. * Set the render list (meshes to be rendered) used in the G buffer.
  63976. */
  63977. set: function (meshes) {
  63978. this._multiRenderTarget.renderList = meshes;
  63979. },
  63980. enumerable: true,
  63981. configurable: true
  63982. });
  63983. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  63984. /**
  63985. * Gets wether or not G buffer are supported by the running hardware.
  63986. * This requires draw buffer supports
  63987. */
  63988. get: function () {
  63989. return this._multiRenderTarget.isSupported;
  63990. },
  63991. enumerable: true,
  63992. configurable: true
  63993. });
  63994. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  63995. /**
  63996. * Gets wether or not position are enabled for the G buffer.
  63997. */
  63998. get: function () {
  63999. return this._enablePosition;
  64000. },
  64001. /**
  64002. * Sets wether or not position are enabled for the G buffer.
  64003. */
  64004. set: function (enable) {
  64005. this._enablePosition = enable;
  64006. this.dispose();
  64007. this._createRenderTargets();
  64008. },
  64009. enumerable: true,
  64010. configurable: true
  64011. });
  64012. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  64013. /**
  64014. * Gets the scene associated with the buffer.
  64015. */
  64016. get: function () {
  64017. return this._scene;
  64018. },
  64019. enumerable: true,
  64020. configurable: true
  64021. });
  64022. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  64023. /**
  64024. * Gets the ratio used by the buffer during its creation.
  64025. * How big is the buffer related to the main canvas.
  64026. */
  64027. get: function () {
  64028. return this._ratio;
  64029. },
  64030. enumerable: true,
  64031. configurable: true
  64032. });
  64033. /**
  64034. * Checks wether everything is ready to render a submesh to the G buffer.
  64035. * @param subMesh the submesh to check readiness for
  64036. * @param useInstances is the mesh drawn using instance or not
  64037. * @returns true if ready otherwise false
  64038. */
  64039. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  64040. var material = subMesh.getMaterial();
  64041. if (material && material.disableDepthWrite) {
  64042. return false;
  64043. }
  64044. var defines = [];
  64045. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  64046. var mesh = subMesh.getMesh();
  64047. // Alpha test
  64048. if (material && material.needAlphaTesting()) {
  64049. defines.push("#define ALPHATEST");
  64050. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  64051. attribs.push(BABYLON.VertexBuffer.UVKind);
  64052. defines.push("#define UV1");
  64053. }
  64054. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  64055. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  64056. defines.push("#define UV2");
  64057. }
  64058. }
  64059. // Buffers
  64060. if (this._enablePosition) {
  64061. defines.push("#define POSITION");
  64062. }
  64063. // Bones
  64064. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  64065. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  64066. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  64067. if (mesh.numBoneInfluencers > 4) {
  64068. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  64069. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  64070. }
  64071. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  64072. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  64073. }
  64074. else {
  64075. defines.push("#define NUM_BONE_INFLUENCERS 0");
  64076. }
  64077. // Instances
  64078. if (useInstances) {
  64079. defines.push("#define INSTANCES");
  64080. attribs.push("world0");
  64081. attribs.push("world1");
  64082. attribs.push("world2");
  64083. attribs.push("world3");
  64084. }
  64085. // Get correct effect
  64086. var join = defines.join("\n");
  64087. if (this._cachedDefines !== join) {
  64088. this._cachedDefines = join;
  64089. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  64090. }
  64091. return this._effect.isReady();
  64092. };
  64093. /**
  64094. * Gets the current underlying G Buffer.
  64095. * @returns the buffer
  64096. */
  64097. GeometryBufferRenderer.prototype.getGBuffer = function () {
  64098. return this._multiRenderTarget;
  64099. };
  64100. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  64101. /**
  64102. * Gets the number of samples used to render the buffer (anti aliasing).
  64103. */
  64104. get: function () {
  64105. return this._multiRenderTarget.samples;
  64106. },
  64107. /**
  64108. * Sets the number of samples used to render the buffer (anti aliasing).
  64109. */
  64110. set: function (value) {
  64111. this._multiRenderTarget.samples = value;
  64112. },
  64113. enumerable: true,
  64114. configurable: true
  64115. });
  64116. /**
  64117. * Disposes the renderer and frees up associated resources.
  64118. */
  64119. GeometryBufferRenderer.prototype.dispose = function () {
  64120. this.getGBuffer().dispose();
  64121. };
  64122. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  64123. var _this = this;
  64124. var engine = this._scene.getEngine();
  64125. var count = this._enablePosition ? 3 : 2;
  64126. this._multiRenderTarget = new BABYLON.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true, defaultType: BABYLON.Engine.TEXTURETYPE_FLOAT });
  64127. if (!this.isSupported) {
  64128. return;
  64129. }
  64130. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64131. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64132. this._multiRenderTarget.refreshRate = 1;
  64133. this._multiRenderTarget.renderParticles = false;
  64134. this._multiRenderTarget.renderList = null;
  64135. // set default depth value to 1.0 (far away)
  64136. this._multiRenderTarget.onClearObservable.add(function (engine) {
  64137. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  64138. });
  64139. // Custom render function
  64140. var renderSubMesh = function (subMesh) {
  64141. var mesh = subMesh.getRenderingMesh();
  64142. var scene = _this._scene;
  64143. var engine = scene.getEngine();
  64144. var material = subMesh.getMaterial();
  64145. if (!material) {
  64146. return;
  64147. }
  64148. // Culling
  64149. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  64150. // Managing instances
  64151. var batch = mesh._getInstancesRenderList(subMesh._id);
  64152. if (batch.mustReturn) {
  64153. return;
  64154. }
  64155. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  64156. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  64157. engine.enableEffect(_this._effect);
  64158. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  64159. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  64160. _this._effect.setMatrix("view", scene.getViewMatrix());
  64161. // Alpha test
  64162. if (material && material.needAlphaTesting()) {
  64163. var alphaTexture = material.getAlphaTestTexture();
  64164. if (alphaTexture) {
  64165. _this._effect.setTexture("diffuseSampler", alphaTexture);
  64166. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  64167. }
  64168. }
  64169. // Bones
  64170. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  64171. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  64172. }
  64173. // Draw
  64174. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  64175. }
  64176. };
  64177. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  64178. var index;
  64179. if (depthOnlySubMeshes.length) {
  64180. engine.setColorWrite(false);
  64181. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  64182. renderSubMesh(depthOnlySubMeshes.data[index]);
  64183. }
  64184. engine.setColorWrite(true);
  64185. }
  64186. for (index = 0; index < opaqueSubMeshes.length; index++) {
  64187. renderSubMesh(opaqueSubMeshes.data[index]);
  64188. }
  64189. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  64190. renderSubMesh(alphaTestSubMeshes.data[index]);
  64191. }
  64192. };
  64193. };
  64194. return GeometryBufferRenderer;
  64195. }());
  64196. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  64197. })(BABYLON || (BABYLON = {}));
  64198. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  64199. var BABYLON;
  64200. (function (BABYLON) {
  64201. var RefractionPostProcess = /** @class */ (function (_super) {
  64202. __extends(RefractionPostProcess, _super);
  64203. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  64204. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  64205. _this.color = color;
  64206. _this.depth = depth;
  64207. _this.colorLevel = colorLevel;
  64208. _this.onActivateObservable.add(function (cam) {
  64209. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  64210. });
  64211. _this.onApplyObservable.add(function (effect) {
  64212. effect.setColor3("baseColor", _this.color);
  64213. effect.setFloat("depth", _this.depth);
  64214. effect.setFloat("colorLevel", _this.colorLevel);
  64215. effect.setTexture("refractionSampler", _this._refRexture);
  64216. });
  64217. return _this;
  64218. }
  64219. // Methods
  64220. RefractionPostProcess.prototype.dispose = function (camera) {
  64221. if (this._refRexture) {
  64222. this._refRexture.dispose();
  64223. }
  64224. _super.prototype.dispose.call(this, camera);
  64225. };
  64226. return RefractionPostProcess;
  64227. }(BABYLON.PostProcess));
  64228. BABYLON.RefractionPostProcess = RefractionPostProcess;
  64229. })(BABYLON || (BABYLON = {}));
  64230. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  64231. var BABYLON;
  64232. (function (BABYLON) {
  64233. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  64234. __extends(BlackAndWhitePostProcess, _super);
  64235. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  64236. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  64237. _this.degree = 1;
  64238. _this.onApplyObservable.add(function (effect) {
  64239. effect.setFloat("degree", _this.degree);
  64240. });
  64241. return _this;
  64242. }
  64243. return BlackAndWhitePostProcess;
  64244. }(BABYLON.PostProcess));
  64245. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  64246. })(BABYLON || (BABYLON = {}));
  64247. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  64248. var BABYLON;
  64249. (function (BABYLON) {
  64250. var ConvolutionPostProcess = /** @class */ (function (_super) {
  64251. __extends(ConvolutionPostProcess, _super);
  64252. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  64253. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  64254. _this.kernel = kernel;
  64255. _this.onApply = function (effect) {
  64256. effect.setFloat2("screenSize", _this.width, _this.height);
  64257. effect.setArray("kernel", _this.kernel);
  64258. };
  64259. return _this;
  64260. }
  64261. // Statics
  64262. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  64263. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  64264. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  64265. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  64266. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  64267. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  64268. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  64269. return ConvolutionPostProcess;
  64270. }(BABYLON.PostProcess));
  64271. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  64272. })(BABYLON || (BABYLON = {}));
  64273. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  64274. var BABYLON;
  64275. (function (BABYLON) {
  64276. var FilterPostProcess = /** @class */ (function (_super) {
  64277. __extends(FilterPostProcess, _super);
  64278. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  64279. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  64280. _this.kernelMatrix = kernelMatrix;
  64281. _this.onApply = function (effect) {
  64282. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  64283. };
  64284. return _this;
  64285. }
  64286. return FilterPostProcess;
  64287. }(BABYLON.PostProcess));
  64288. BABYLON.FilterPostProcess = FilterPostProcess;
  64289. })(BABYLON || (BABYLON = {}));
  64290. //# sourceMappingURL=babylon.filterPostProcess.js.map
  64291. var BABYLON;
  64292. (function (BABYLON) {
  64293. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  64294. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  64295. __extends(VolumetricLightScatteringPostProcess, _super);
  64296. /**
  64297. * @constructor
  64298. * @param {string} name - The post-process name
  64299. * @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)
  64300. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  64301. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  64302. * @param {number} samples - The post-process quality, default 100
  64303. * @param {number} samplingMode - The post-process filtering mode
  64304. * @param {BABYLON.Engine} engine - The babylon engine
  64305. * @param {boolean} reusable - If the post-process is reusable
  64306. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  64307. */
  64308. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  64309. if (samples === void 0) { samples = 100; }
  64310. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  64311. 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;
  64312. _this._screenCoordinates = BABYLON.Vector2.Zero();
  64313. /**
  64314. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  64315. * @type {Vector3}
  64316. */
  64317. _this.customMeshPosition = BABYLON.Vector3.Zero();
  64318. /**
  64319. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  64320. * @type {boolean}
  64321. */
  64322. _this.useCustomMeshPosition = false;
  64323. /**
  64324. * If the post-process should inverse the light scattering direction
  64325. * @type {boolean}
  64326. */
  64327. _this.invert = true;
  64328. /**
  64329. * Array containing the excluded meshes not rendered in the internal pass
  64330. */
  64331. _this.excludedMeshes = new Array();
  64332. /**
  64333. * Controls the overall intensity of the post-process
  64334. * @type {number}
  64335. */
  64336. _this.exposure = 0.3;
  64337. /**
  64338. * Dissipates each sample's contribution in range [0, 1]
  64339. * @type {number}
  64340. */
  64341. _this.decay = 0.96815;
  64342. /**
  64343. * Controls the overall intensity of each sample
  64344. * @type {number}
  64345. */
  64346. _this.weight = 0.58767;
  64347. /**
  64348. * Controls the density of each sample
  64349. * @type {number}
  64350. */
  64351. _this.density = 0.926;
  64352. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  64353. engine = scene.getEngine();
  64354. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  64355. // Configure mesh
  64356. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  64357. // Configure
  64358. _this._createPass(scene, ratio.passRatio || ratio);
  64359. _this.onActivate = function (camera) {
  64360. if (!_this.isSupported) {
  64361. _this.dispose(camera);
  64362. }
  64363. _this.onActivate = null;
  64364. };
  64365. _this.onApplyObservable.add(function (effect) {
  64366. _this._updateMeshScreenCoordinates(scene);
  64367. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  64368. effect.setFloat("exposure", _this.exposure);
  64369. effect.setFloat("decay", _this.decay);
  64370. effect.setFloat("weight", _this.weight);
  64371. effect.setFloat("density", _this.density);
  64372. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  64373. });
  64374. return _this;
  64375. }
  64376. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  64377. get: function () {
  64378. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  64379. return false;
  64380. },
  64381. set: function (useDiffuseColor) {
  64382. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  64383. },
  64384. enumerable: true,
  64385. configurable: true
  64386. });
  64387. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  64388. return "VolumetricLightScatteringPostProcess";
  64389. };
  64390. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  64391. var mesh = subMesh.getMesh();
  64392. // Render this.mesh as default
  64393. if (mesh === this.mesh && mesh.material) {
  64394. return mesh.material.isReady(mesh);
  64395. }
  64396. var defines = [];
  64397. var attribs = [BABYLON.VertexBuffer.PositionKind];
  64398. var material = subMesh.getMaterial();
  64399. // Alpha test
  64400. if (material) {
  64401. if (material.needAlphaTesting()) {
  64402. defines.push("#define ALPHATEST");
  64403. }
  64404. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  64405. attribs.push(BABYLON.VertexBuffer.UVKind);
  64406. defines.push("#define UV1");
  64407. }
  64408. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  64409. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  64410. defines.push("#define UV2");
  64411. }
  64412. }
  64413. // Bones
  64414. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  64415. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  64416. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  64417. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  64418. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  64419. }
  64420. else {
  64421. defines.push("#define NUM_BONE_INFLUENCERS 0");
  64422. }
  64423. // Instances
  64424. if (useInstances) {
  64425. defines.push("#define INSTANCES");
  64426. attribs.push("world0");
  64427. attribs.push("world1");
  64428. attribs.push("world2");
  64429. attribs.push("world3");
  64430. }
  64431. // Get correct effect
  64432. var join = defines.join("\n");
  64433. if (this._cachedDefines !== join) {
  64434. this._cachedDefines = join;
  64435. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  64436. }
  64437. return this._volumetricLightScatteringPass.isReady();
  64438. };
  64439. /**
  64440. * Sets the new light position for light scattering effect
  64441. * @param {BABYLON.Vector3} The new custom light position
  64442. */
  64443. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  64444. this.customMeshPosition = position;
  64445. };
  64446. /**
  64447. * Returns the light position for light scattering effect
  64448. * @return {BABYLON.Vector3} The custom light position
  64449. */
  64450. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  64451. return this.customMeshPosition;
  64452. };
  64453. /**
  64454. * Disposes the internal assets and detaches the post-process from the camera
  64455. */
  64456. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  64457. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  64458. if (rttIndex !== -1) {
  64459. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  64460. }
  64461. this._volumetricLightScatteringRTT.dispose();
  64462. _super.prototype.dispose.call(this, camera);
  64463. };
  64464. /**
  64465. * Returns the render target texture used by the post-process
  64466. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  64467. */
  64468. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  64469. return this._volumetricLightScatteringRTT;
  64470. };
  64471. // Private methods
  64472. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  64473. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  64474. return true;
  64475. }
  64476. return false;
  64477. };
  64478. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  64479. var _this = this;
  64480. var engine = scene.getEngine();
  64481. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  64482. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64483. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64484. this._volumetricLightScatteringRTT.renderList = null;
  64485. this._volumetricLightScatteringRTT.renderParticles = false;
  64486. var camera = this.getCamera();
  64487. if (camera) {
  64488. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  64489. }
  64490. else {
  64491. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  64492. }
  64493. // Custom render function for submeshes
  64494. var renderSubMesh = function (subMesh) {
  64495. var mesh = subMesh.getRenderingMesh();
  64496. if (_this._meshExcluded(mesh)) {
  64497. return;
  64498. }
  64499. var material = subMesh.getMaterial();
  64500. if (!material) {
  64501. return;
  64502. }
  64503. var scene = mesh.getScene();
  64504. var engine = scene.getEngine();
  64505. // Culling
  64506. engine.setState(material.backFaceCulling);
  64507. // Managing instances
  64508. var batch = mesh._getInstancesRenderList(subMesh._id);
  64509. if (batch.mustReturn) {
  64510. return;
  64511. }
  64512. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  64513. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  64514. var effect = _this._volumetricLightScatteringPass;
  64515. if (mesh === _this.mesh) {
  64516. if (subMesh.effect) {
  64517. effect = subMesh.effect;
  64518. }
  64519. else {
  64520. effect = material.getEffect();
  64521. }
  64522. }
  64523. engine.enableEffect(effect);
  64524. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  64525. if (mesh === _this.mesh) {
  64526. material.bind(mesh.getWorldMatrix(), mesh);
  64527. }
  64528. else {
  64529. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  64530. // Alpha test
  64531. if (material && material.needAlphaTesting()) {
  64532. var alphaTexture = material.getAlphaTestTexture();
  64533. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  64534. if (alphaTexture) {
  64535. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  64536. }
  64537. }
  64538. // Bones
  64539. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  64540. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  64541. }
  64542. }
  64543. // Draw
  64544. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  64545. }
  64546. };
  64547. // Render target texture callbacks
  64548. var savedSceneClearColor;
  64549. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  64550. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  64551. savedSceneClearColor = scene.clearColor;
  64552. scene.clearColor = sceneClearColor;
  64553. });
  64554. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  64555. scene.clearColor = savedSceneClearColor;
  64556. });
  64557. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  64558. var engine = scene.getEngine();
  64559. var index;
  64560. if (depthOnlySubMeshes.length) {
  64561. engine.setColorWrite(false);
  64562. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  64563. renderSubMesh(depthOnlySubMeshes.data[index]);
  64564. }
  64565. engine.setColorWrite(true);
  64566. }
  64567. for (index = 0; index < opaqueSubMeshes.length; index++) {
  64568. renderSubMesh(opaqueSubMeshes.data[index]);
  64569. }
  64570. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  64571. renderSubMesh(alphaTestSubMeshes.data[index]);
  64572. }
  64573. if (transparentSubMeshes.length) {
  64574. // Sort sub meshes
  64575. for (index = 0; index < transparentSubMeshes.length; index++) {
  64576. var submesh = transparentSubMeshes.data[index];
  64577. var boundingInfo = submesh.getBoundingInfo();
  64578. if (boundingInfo && scene.activeCamera) {
  64579. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  64580. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  64581. }
  64582. }
  64583. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  64584. sortedArray.sort(function (a, b) {
  64585. // Alpha index first
  64586. if (a._alphaIndex > b._alphaIndex) {
  64587. return 1;
  64588. }
  64589. if (a._alphaIndex < b._alphaIndex) {
  64590. return -1;
  64591. }
  64592. // Then distance to camera
  64593. if (a._distanceToCamera < b._distanceToCamera) {
  64594. return 1;
  64595. }
  64596. if (a._distanceToCamera > b._distanceToCamera) {
  64597. return -1;
  64598. }
  64599. return 0;
  64600. });
  64601. // Render sub meshes
  64602. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  64603. for (index = 0; index < sortedArray.length; index++) {
  64604. renderSubMesh(sortedArray[index]);
  64605. }
  64606. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  64607. }
  64608. };
  64609. };
  64610. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  64611. var transform = scene.getTransformMatrix();
  64612. var meshPosition;
  64613. if (this.useCustomMeshPosition) {
  64614. meshPosition = this.customMeshPosition;
  64615. }
  64616. else if (this.attachedNode) {
  64617. meshPosition = this.attachedNode.position;
  64618. }
  64619. else {
  64620. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  64621. }
  64622. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  64623. this._screenCoordinates.x = pos.x / this._viewPort.width;
  64624. this._screenCoordinates.y = pos.y / this._viewPort.height;
  64625. if (this.invert)
  64626. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  64627. };
  64628. // Static methods
  64629. /**
  64630. * Creates a default mesh for the Volumeric Light Scattering post-process
  64631. * @param {string} The mesh name
  64632. * @param {BABYLON.Scene} The scene where to create the mesh
  64633. * @return {BABYLON.Mesh} the default mesh
  64634. */
  64635. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  64636. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  64637. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  64638. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  64639. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  64640. mesh.material = material;
  64641. return mesh;
  64642. };
  64643. __decorate([
  64644. BABYLON.serializeAsVector3()
  64645. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  64646. __decorate([
  64647. BABYLON.serialize()
  64648. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  64649. __decorate([
  64650. BABYLON.serialize()
  64651. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  64652. __decorate([
  64653. BABYLON.serializeAsMeshReference()
  64654. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  64655. __decorate([
  64656. BABYLON.serialize()
  64657. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  64658. __decorate([
  64659. BABYLON.serialize()
  64660. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  64661. __decorate([
  64662. BABYLON.serialize()
  64663. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  64664. __decorate([
  64665. BABYLON.serialize()
  64666. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  64667. __decorate([
  64668. BABYLON.serialize()
  64669. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  64670. return VolumetricLightScatteringPostProcess;
  64671. }(BABYLON.PostProcess));
  64672. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  64673. })(BABYLON || (BABYLON = {}));
  64674. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  64675. //
  64676. // This post-process allows the modification of rendered colors by using
  64677. // a 'look-up table' (LUT). This effect is also called Color Grading.
  64678. //
  64679. // The object needs to be provided an url to a texture containing the color
  64680. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  64681. // Use an image editing software to tweak the LUT to match your needs.
  64682. //
  64683. // For an example of a color LUT, see here:
  64684. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  64685. // For explanations on color grading, see here:
  64686. // http://udn.epicgames.com/Three/ColorGrading.html
  64687. //
  64688. var BABYLON;
  64689. (function (BABYLON) {
  64690. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  64691. __extends(ColorCorrectionPostProcess, _super);
  64692. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  64693. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  64694. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  64695. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  64696. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64697. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64698. _this.onApply = function (effect) {
  64699. effect.setTexture("colorTable", _this._colorTableTexture);
  64700. };
  64701. return _this;
  64702. }
  64703. return ColorCorrectionPostProcess;
  64704. }(BABYLON.PostProcess));
  64705. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  64706. })(BABYLON || (BABYLON = {}));
  64707. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  64708. var BABYLON;
  64709. (function (BABYLON) {
  64710. var TonemappingOperator;
  64711. (function (TonemappingOperator) {
  64712. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  64713. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  64714. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  64715. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  64716. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  64717. ;
  64718. var TonemapPostProcess = /** @class */ (function (_super) {
  64719. __extends(TonemapPostProcess, _super);
  64720. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  64721. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  64722. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64723. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  64724. _this._operator = _operator;
  64725. _this.exposureAdjustment = exposureAdjustment;
  64726. var defines = "#define ";
  64727. if (_this._operator === TonemappingOperator.Hable)
  64728. defines += "HABLE_TONEMAPPING";
  64729. else if (_this._operator === TonemappingOperator.Reinhard)
  64730. defines += "REINHARD_TONEMAPPING";
  64731. else if (_this._operator === TonemappingOperator.HejiDawson)
  64732. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  64733. else if (_this._operator === TonemappingOperator.Photographic)
  64734. defines += "PHOTOGRAPHIC_TONEMAPPING";
  64735. //sadly a second call to create the effect.
  64736. _this.updateEffect(defines);
  64737. _this.onApply = function (effect) {
  64738. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  64739. };
  64740. return _this;
  64741. }
  64742. return TonemapPostProcess;
  64743. }(BABYLON.PostProcess));
  64744. BABYLON.TonemapPostProcess = TonemapPostProcess;
  64745. })(BABYLON || (BABYLON = {}));
  64746. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  64747. var BABYLON;
  64748. (function (BABYLON) {
  64749. var DisplayPassPostProcess = /** @class */ (function (_super) {
  64750. __extends(DisplayPassPostProcess, _super);
  64751. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  64752. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  64753. }
  64754. return DisplayPassPostProcess;
  64755. }(BABYLON.PostProcess));
  64756. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  64757. })(BABYLON || (BABYLON = {}));
  64758. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  64759. var BABYLON;
  64760. (function (BABYLON) {
  64761. var HighlightsPostProcess = /** @class */ (function (_super) {
  64762. __extends(HighlightsPostProcess, _super);
  64763. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  64764. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64765. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  64766. }
  64767. return HighlightsPostProcess;
  64768. }(BABYLON.PostProcess));
  64769. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  64770. })(BABYLON || (BABYLON = {}));
  64771. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  64772. var BABYLON;
  64773. (function (BABYLON) {
  64774. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  64775. __extends(ImageProcessingPostProcess, _super);
  64776. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  64777. if (camera === void 0) { camera = null; }
  64778. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64779. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  64780. _this._fromLinearSpace = true;
  64781. /**
  64782. * Defines cache preventing GC.
  64783. */
  64784. _this._defines = {
  64785. IMAGEPROCESSING: false,
  64786. VIGNETTE: false,
  64787. VIGNETTEBLENDMODEMULTIPLY: false,
  64788. VIGNETTEBLENDMODEOPAQUE: false,
  64789. TONEMAPPING: false,
  64790. CONTRAST: false,
  64791. COLORCURVES: false,
  64792. COLORGRADING: false,
  64793. COLORGRADING3D: false,
  64794. FROMLINEARSPACE: false,
  64795. SAMPLER3DGREENDEPTH: false,
  64796. SAMPLER3DBGRMAP: false,
  64797. IMAGEPROCESSINGPOSTPROCESS: false,
  64798. EXPOSURE: false,
  64799. };
  64800. // Setup the configuration as forced by the constructor. This would then not force the
  64801. // scene materials output in linear space and let untouched the default forward pass.
  64802. if (imageProcessingConfiguration) {
  64803. imageProcessingConfiguration.applyByPostProcess = true;
  64804. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  64805. // This will cause the shader to be compiled
  64806. _this.fromLinearSpace = false;
  64807. }
  64808. else {
  64809. _this._attachImageProcessingConfiguration(null, true);
  64810. _this.imageProcessingConfiguration.applyByPostProcess = true;
  64811. }
  64812. _this.onApply = function (effect) {
  64813. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  64814. };
  64815. return _this;
  64816. }
  64817. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  64818. /**
  64819. * Gets the image processing configuration used either in this material.
  64820. */
  64821. get: function () {
  64822. return this._imageProcessingConfiguration;
  64823. },
  64824. /**
  64825. * Sets the Default image processing configuration used either in the this material.
  64826. *
  64827. * If sets to null, the scene one is in use.
  64828. */
  64829. set: function (value) {
  64830. this._attachImageProcessingConfiguration(value);
  64831. },
  64832. enumerable: true,
  64833. configurable: true
  64834. });
  64835. /**
  64836. * Attaches a new image processing configuration to the PBR Material.
  64837. * @param configuration
  64838. */
  64839. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  64840. var _this = this;
  64841. if (doNotBuild === void 0) { doNotBuild = false; }
  64842. if (configuration === this._imageProcessingConfiguration) {
  64843. return;
  64844. }
  64845. // Detaches observer.
  64846. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  64847. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  64848. }
  64849. // Pick the scene configuration if needed.
  64850. if (!configuration) {
  64851. var scene = null;
  64852. var engine = this.getEngine();
  64853. var camera = this.getCamera();
  64854. if (camera) {
  64855. scene = camera.getScene();
  64856. }
  64857. else if (engine && engine.scenes) {
  64858. var scenes = engine.scenes;
  64859. scene = scenes[scenes.length - 1];
  64860. }
  64861. else {
  64862. scene = BABYLON.Engine.LastCreatedScene;
  64863. }
  64864. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  64865. }
  64866. else {
  64867. this._imageProcessingConfiguration = configuration;
  64868. }
  64869. // Attaches observer.
  64870. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  64871. _this._updateParameters();
  64872. });
  64873. // Ensure the effect will be rebuilt.
  64874. if (!doNotBuild) {
  64875. this._updateParameters();
  64876. }
  64877. };
  64878. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  64879. /**
  64880. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  64881. */
  64882. get: function () {
  64883. return this.imageProcessingConfiguration.colorCurves;
  64884. },
  64885. /**
  64886. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  64887. */
  64888. set: function (value) {
  64889. this.imageProcessingConfiguration.colorCurves = value;
  64890. },
  64891. enumerable: true,
  64892. configurable: true
  64893. });
  64894. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  64895. /**
  64896. * Gets wether the color curves effect is enabled.
  64897. */
  64898. get: function () {
  64899. return this.imageProcessingConfiguration.colorCurvesEnabled;
  64900. },
  64901. /**
  64902. * Sets wether the color curves effect is enabled.
  64903. */
  64904. set: function (value) {
  64905. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  64906. },
  64907. enumerable: true,
  64908. configurable: true
  64909. });
  64910. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  64911. /**
  64912. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  64913. */
  64914. get: function () {
  64915. return this.imageProcessingConfiguration.colorGradingTexture;
  64916. },
  64917. /**
  64918. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  64919. */
  64920. set: function (value) {
  64921. this.imageProcessingConfiguration.colorGradingTexture = value;
  64922. },
  64923. enumerable: true,
  64924. configurable: true
  64925. });
  64926. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  64927. /**
  64928. * Gets wether the color grading effect is enabled.
  64929. */
  64930. get: function () {
  64931. return this.imageProcessingConfiguration.colorGradingEnabled;
  64932. },
  64933. /**
  64934. * Gets wether the color grading effect is enabled.
  64935. */
  64936. set: function (value) {
  64937. this.imageProcessingConfiguration.colorGradingEnabled = value;
  64938. },
  64939. enumerable: true,
  64940. configurable: true
  64941. });
  64942. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  64943. /**
  64944. * Gets exposure used in the effect.
  64945. */
  64946. get: function () {
  64947. return this.imageProcessingConfiguration.exposure;
  64948. },
  64949. /**
  64950. * Sets exposure used in the effect.
  64951. */
  64952. set: function (value) {
  64953. this.imageProcessingConfiguration.exposure = value;
  64954. },
  64955. enumerable: true,
  64956. configurable: true
  64957. });
  64958. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  64959. /**
  64960. * Gets wether tonemapping is enabled or not.
  64961. */
  64962. get: function () {
  64963. return this._imageProcessingConfiguration.toneMappingEnabled;
  64964. },
  64965. /**
  64966. * Sets wether tonemapping is enabled or not
  64967. */
  64968. set: function (value) {
  64969. this._imageProcessingConfiguration.toneMappingEnabled = value;
  64970. },
  64971. enumerable: true,
  64972. configurable: true
  64973. });
  64974. ;
  64975. ;
  64976. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  64977. /**
  64978. * Gets contrast used in the effect.
  64979. */
  64980. get: function () {
  64981. return this.imageProcessingConfiguration.contrast;
  64982. },
  64983. /**
  64984. * Sets contrast used in the effect.
  64985. */
  64986. set: function (value) {
  64987. this.imageProcessingConfiguration.contrast = value;
  64988. },
  64989. enumerable: true,
  64990. configurable: true
  64991. });
  64992. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  64993. /**
  64994. * Gets Vignette stretch size.
  64995. */
  64996. get: function () {
  64997. return this.imageProcessingConfiguration.vignetteStretch;
  64998. },
  64999. /**
  65000. * Sets Vignette stretch size.
  65001. */
  65002. set: function (value) {
  65003. this.imageProcessingConfiguration.vignetteStretch = value;
  65004. },
  65005. enumerable: true,
  65006. configurable: true
  65007. });
  65008. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  65009. /**
  65010. * Gets Vignette centre X Offset.
  65011. */
  65012. get: function () {
  65013. return this.imageProcessingConfiguration.vignetteCentreX;
  65014. },
  65015. /**
  65016. * Sets Vignette centre X Offset.
  65017. */
  65018. set: function (value) {
  65019. this.imageProcessingConfiguration.vignetteCentreX = value;
  65020. },
  65021. enumerable: true,
  65022. configurable: true
  65023. });
  65024. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  65025. /**
  65026. * Gets Vignette centre Y Offset.
  65027. */
  65028. get: function () {
  65029. return this.imageProcessingConfiguration.vignetteCentreY;
  65030. },
  65031. /**
  65032. * Sets Vignette centre Y Offset.
  65033. */
  65034. set: function (value) {
  65035. this.imageProcessingConfiguration.vignetteCentreY = value;
  65036. },
  65037. enumerable: true,
  65038. configurable: true
  65039. });
  65040. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  65041. /**
  65042. * Gets Vignette weight or intensity of the vignette effect.
  65043. */
  65044. get: function () {
  65045. return this.imageProcessingConfiguration.vignetteWeight;
  65046. },
  65047. /**
  65048. * Sets Vignette weight or intensity of the vignette effect.
  65049. */
  65050. set: function (value) {
  65051. this.imageProcessingConfiguration.vignetteWeight = value;
  65052. },
  65053. enumerable: true,
  65054. configurable: true
  65055. });
  65056. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  65057. /**
  65058. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  65059. * if vignetteEnabled is set to true.
  65060. */
  65061. get: function () {
  65062. return this.imageProcessingConfiguration.vignetteColor;
  65063. },
  65064. /**
  65065. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  65066. * if vignetteEnabled is set to true.
  65067. */
  65068. set: function (value) {
  65069. this.imageProcessingConfiguration.vignetteColor = value;
  65070. },
  65071. enumerable: true,
  65072. configurable: true
  65073. });
  65074. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  65075. /**
  65076. * Gets Camera field of view used by the Vignette effect.
  65077. */
  65078. get: function () {
  65079. return this.imageProcessingConfiguration.vignetteCameraFov;
  65080. },
  65081. /**
  65082. * Sets Camera field of view used by the Vignette effect.
  65083. */
  65084. set: function (value) {
  65085. this.imageProcessingConfiguration.vignetteCameraFov = value;
  65086. },
  65087. enumerable: true,
  65088. configurable: true
  65089. });
  65090. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  65091. /**
  65092. * Gets the vignette blend mode allowing different kind of effect.
  65093. */
  65094. get: function () {
  65095. return this.imageProcessingConfiguration.vignetteBlendMode;
  65096. },
  65097. /**
  65098. * Sets the vignette blend mode allowing different kind of effect.
  65099. */
  65100. set: function (value) {
  65101. this.imageProcessingConfiguration.vignetteBlendMode = value;
  65102. },
  65103. enumerable: true,
  65104. configurable: true
  65105. });
  65106. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  65107. /**
  65108. * Gets wether the vignette effect is enabled.
  65109. */
  65110. get: function () {
  65111. return this.imageProcessingConfiguration.vignetteEnabled;
  65112. },
  65113. /**
  65114. * Sets wether the vignette effect is enabled.
  65115. */
  65116. set: function (value) {
  65117. this.imageProcessingConfiguration.vignetteEnabled = value;
  65118. },
  65119. enumerable: true,
  65120. configurable: true
  65121. });
  65122. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  65123. /**
  65124. * Gets wether the input of the processing is in Gamma or Linear Space.
  65125. */
  65126. get: function () {
  65127. return this._fromLinearSpace;
  65128. },
  65129. /**
  65130. * Sets wether the input of the processing is in Gamma or Linear Space.
  65131. */
  65132. set: function (value) {
  65133. if (this._fromLinearSpace === value) {
  65134. return;
  65135. }
  65136. this._fromLinearSpace = value;
  65137. this._updateParameters();
  65138. },
  65139. enumerable: true,
  65140. configurable: true
  65141. });
  65142. ImageProcessingPostProcess.prototype.getClassName = function () {
  65143. return "ImageProcessingPostProcess";
  65144. };
  65145. ImageProcessingPostProcess.prototype._updateParameters = function () {
  65146. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  65147. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  65148. var defines = "";
  65149. for (var define in this._defines) {
  65150. if (this._defines[define]) {
  65151. defines += "#define " + define + ";\r\n";
  65152. }
  65153. }
  65154. var samplers = ["textureSampler"];
  65155. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  65156. var uniforms = ["scale"];
  65157. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  65158. this.updateEffect(defines, uniforms, samplers);
  65159. };
  65160. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  65161. _super.prototype.dispose.call(this, camera);
  65162. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  65163. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  65164. }
  65165. this.imageProcessingConfiguration.applyByPostProcess = false;
  65166. };
  65167. __decorate([
  65168. BABYLON.serialize()
  65169. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  65170. return ImageProcessingPostProcess;
  65171. }(BABYLON.PostProcess));
  65172. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  65173. })(BABYLON || (BABYLON = {}));
  65174. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  65175. var BABYLON;
  65176. (function (BABYLON) {
  65177. var BlurPostProcess = /** @class */ (function (_super) {
  65178. __extends(BlurPostProcess, _super);
  65179. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  65180. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  65181. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65182. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  65183. _this.direction = direction;
  65184. _this._packedFloat = false;
  65185. _this.onApplyObservable.add(function (effect) {
  65186. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  65187. });
  65188. _this.kernel = kernel;
  65189. return _this;
  65190. }
  65191. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  65192. /**
  65193. * Gets the length in pixels of the blur sample region
  65194. */
  65195. get: function () {
  65196. return this._idealKernel;
  65197. },
  65198. /**
  65199. * Sets the length in pixels of the blur sample region
  65200. */
  65201. set: function (v) {
  65202. if (this._idealKernel === v) {
  65203. return;
  65204. }
  65205. v = Math.max(v, 1);
  65206. this._idealKernel = v;
  65207. this._kernel = this._nearestBestKernel(v);
  65208. this._updateParameters();
  65209. },
  65210. enumerable: true,
  65211. configurable: true
  65212. });
  65213. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  65214. /**
  65215. * Gets wether or not the blur is unpacking/repacking floats
  65216. */
  65217. get: function () {
  65218. return this._packedFloat;
  65219. },
  65220. /**
  65221. * Sets wether or not the blur needs to unpack/repack floats
  65222. */
  65223. set: function (v) {
  65224. if (this._packedFloat === v) {
  65225. return;
  65226. }
  65227. this._packedFloat = v;
  65228. this._updateParameters();
  65229. },
  65230. enumerable: true,
  65231. configurable: true
  65232. });
  65233. BlurPostProcess.prototype._updateParameters = function () {
  65234. // Generate sampling offsets and weights
  65235. var N = this._kernel;
  65236. var centerIndex = (N - 1) / 2;
  65237. // Generate Gaussian sampling weights over kernel
  65238. var offsets = [];
  65239. var weights = [];
  65240. var totalWeight = 0;
  65241. for (var i = 0; i < N; i++) {
  65242. var u = i / (N - 1);
  65243. var w = this._gaussianWeight(u * 2.0 - 1);
  65244. offsets[i] = (i - centerIndex);
  65245. weights[i] = w;
  65246. totalWeight += w;
  65247. }
  65248. // Normalize weights
  65249. for (var i = 0; i < weights.length; i++) {
  65250. weights[i] /= totalWeight;
  65251. }
  65252. // Optimize: combine samples to take advantage of hardware linear sampling
  65253. // Walk from left to center, combining pairs (symmetrically)
  65254. var linearSamplingWeights = [];
  65255. var linearSamplingOffsets = [];
  65256. var linearSamplingMap = [];
  65257. for (var i = 0; i <= centerIndex; i += 2) {
  65258. var j = Math.min(i + 1, Math.floor(centerIndex));
  65259. var singleCenterSample = i === j;
  65260. if (singleCenterSample) {
  65261. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  65262. }
  65263. else {
  65264. var sharedCell = j === centerIndex;
  65265. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  65266. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  65267. if (offsetLinear === 0) {
  65268. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  65269. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  65270. }
  65271. else {
  65272. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  65273. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  65274. }
  65275. }
  65276. }
  65277. for (var i = 0; i < linearSamplingMap.length; i++) {
  65278. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  65279. linearSamplingWeights[i] = linearSamplingMap[i].w;
  65280. }
  65281. // Replace with optimized
  65282. offsets = linearSamplingOffsets;
  65283. weights = linearSamplingWeights;
  65284. // Generate shaders
  65285. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  65286. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  65287. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  65288. var defines = "";
  65289. for (var i = 0; i < varyingCount; i++) {
  65290. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  65291. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  65292. }
  65293. var depCount = 0;
  65294. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  65295. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  65296. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  65297. depCount++;
  65298. }
  65299. if (this.packedFloat) {
  65300. defines += "#define PACKEDFLOAT 1";
  65301. }
  65302. this.updateEffect(defines, null, null, {
  65303. varyingCount: varyingCount,
  65304. depCount: depCount
  65305. });
  65306. };
  65307. /**
  65308. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  65309. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  65310. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  65311. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  65312. * The gaps between physical kernels are compensated for in the weighting of the samples
  65313. * @param idealKernel Ideal blur kernel.
  65314. * @return Nearest best kernel.
  65315. */
  65316. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  65317. var v = Math.round(idealKernel);
  65318. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  65319. var k = _a[_i];
  65320. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  65321. return Math.max(k, 3);
  65322. }
  65323. }
  65324. return Math.max(v, 3);
  65325. };
  65326. /**
  65327. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  65328. * @param x The point on the Gaussian distribution to sample.
  65329. * @return the value of the Gaussian function at x.
  65330. */
  65331. BlurPostProcess.prototype._gaussianWeight = function (x) {
  65332. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  65333. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  65334. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  65335. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  65336. // truncated at around 1.3% of peak strength.
  65337. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  65338. var sigma = (1 / 3);
  65339. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  65340. var exponent = -((x * x) / (2.0 * sigma * sigma));
  65341. var weight = (1.0 / denominator) * Math.exp(exponent);
  65342. return weight;
  65343. };
  65344. /**
  65345. * Generates a string that can be used as a floating point number in GLSL.
  65346. * @param x Value to print.
  65347. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  65348. * @return GLSL float string.
  65349. */
  65350. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  65351. if (decimalFigures === void 0) { decimalFigures = 8; }
  65352. return x.toFixed(decimalFigures).replace(/0+$/, '');
  65353. };
  65354. return BlurPostProcess;
  65355. }(BABYLON.PostProcess));
  65356. BABYLON.BlurPostProcess = BlurPostProcess;
  65357. })(BABYLON || (BABYLON = {}));
  65358. //# sourceMappingURL=babylon.blurPostProcess.js.map
  65359. var BABYLON;
  65360. (function (BABYLON) {
  65361. var Bone = /** @class */ (function (_super) {
  65362. __extends(Bone, _super);
  65363. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  65364. if (parentBone === void 0) { parentBone = null; }
  65365. if (localMatrix === void 0) { localMatrix = null; }
  65366. if (restPose === void 0) { restPose = null; }
  65367. if (baseMatrix === void 0) { baseMatrix = null; }
  65368. if (index === void 0) { index = null; }
  65369. var _this = _super.call(this, name, skeleton.getScene()) || this;
  65370. _this.name = name;
  65371. _this.children = new Array();
  65372. _this.animations = new Array();
  65373. // Set this value to map this bone to a different index in the transform matrices.
  65374. // Set this value to -1 to exclude the bone from the transform matrices.
  65375. _this._index = null;
  65376. _this._worldTransform = new BABYLON.Matrix();
  65377. _this._absoluteTransform = new BABYLON.Matrix();
  65378. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  65379. _this._scaleMatrix = BABYLON.Matrix.Identity();
  65380. _this._scaleVector = BABYLON.Vector3.One();
  65381. _this._negateScaleChildren = BABYLON.Vector3.One();
  65382. _this._scalingDeterminant = 1;
  65383. _this._skeleton = skeleton;
  65384. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  65385. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  65386. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  65387. _this._index = index;
  65388. skeleton.bones.push(_this);
  65389. _this.setParent(parentBone, false);
  65390. _this._updateDifferenceMatrix();
  65391. return _this;
  65392. }
  65393. Object.defineProperty(Bone.prototype, "_matrix", {
  65394. get: function () {
  65395. return this._localMatrix;
  65396. },
  65397. set: function (val) {
  65398. if (this._localMatrix) {
  65399. this._localMatrix.copyFrom(val);
  65400. }
  65401. else {
  65402. this._localMatrix = val;
  65403. }
  65404. },
  65405. enumerable: true,
  65406. configurable: true
  65407. });
  65408. // Members
  65409. Bone.prototype.getSkeleton = function () {
  65410. return this._skeleton;
  65411. };
  65412. Bone.prototype.getParent = function () {
  65413. return this._parent;
  65414. };
  65415. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  65416. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  65417. if (this._parent === parent) {
  65418. return;
  65419. }
  65420. if (this._parent) {
  65421. var index = this._parent.children.indexOf(this);
  65422. if (index !== -1) {
  65423. this._parent.children.splice(index, 1);
  65424. }
  65425. }
  65426. this._parent = parent;
  65427. if (this._parent) {
  65428. this._parent.children.push(this);
  65429. }
  65430. if (updateDifferenceMatrix) {
  65431. this._updateDifferenceMatrix();
  65432. }
  65433. };
  65434. Bone.prototype.getLocalMatrix = function () {
  65435. return this._localMatrix;
  65436. };
  65437. Bone.prototype.getBaseMatrix = function () {
  65438. return this._baseMatrix;
  65439. };
  65440. Bone.prototype.getRestPose = function () {
  65441. return this._restPose;
  65442. };
  65443. Bone.prototype.returnToRest = function () {
  65444. this.updateMatrix(this._restPose.clone());
  65445. };
  65446. Bone.prototype.getWorldMatrix = function () {
  65447. return this._worldTransform;
  65448. };
  65449. Bone.prototype.getInvertedAbsoluteTransform = function () {
  65450. return this._invertedAbsoluteTransform;
  65451. };
  65452. Bone.prototype.getAbsoluteTransform = function () {
  65453. return this._absoluteTransform;
  65454. };
  65455. Object.defineProperty(Bone.prototype, "position", {
  65456. // Properties (matches AbstractMesh properties)
  65457. get: function () {
  65458. return this.getPosition();
  65459. },
  65460. set: function (newPosition) {
  65461. this.setPosition(newPosition);
  65462. },
  65463. enumerable: true,
  65464. configurable: true
  65465. });
  65466. Object.defineProperty(Bone.prototype, "rotation", {
  65467. get: function () {
  65468. return this.getRotation();
  65469. },
  65470. set: function (newRotation) {
  65471. this.setRotation(newRotation);
  65472. },
  65473. enumerable: true,
  65474. configurable: true
  65475. });
  65476. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  65477. get: function () {
  65478. return this.getRotationQuaternion();
  65479. },
  65480. set: function (newRotation) {
  65481. this.setRotationQuaternion(newRotation);
  65482. },
  65483. enumerable: true,
  65484. configurable: true
  65485. });
  65486. Object.defineProperty(Bone.prototype, "scaling", {
  65487. get: function () {
  65488. return this.getScale();
  65489. },
  65490. set: function (newScaling) {
  65491. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  65492. },
  65493. enumerable: true,
  65494. configurable: true
  65495. });
  65496. // Methods
  65497. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  65498. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  65499. this._baseMatrix = matrix.clone();
  65500. this._localMatrix = matrix.clone();
  65501. this._skeleton._markAsDirty();
  65502. if (updateDifferenceMatrix) {
  65503. this._updateDifferenceMatrix();
  65504. }
  65505. };
  65506. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  65507. if (!rootMatrix) {
  65508. rootMatrix = this._baseMatrix;
  65509. }
  65510. if (this._parent) {
  65511. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  65512. }
  65513. else {
  65514. this._absoluteTransform.copyFrom(rootMatrix);
  65515. }
  65516. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  65517. for (var index = 0; index < this.children.length; index++) {
  65518. this.children[index]._updateDifferenceMatrix();
  65519. }
  65520. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  65521. };
  65522. Bone.prototype.markAsDirty = function () {
  65523. this._currentRenderId++;
  65524. this._skeleton._markAsDirty();
  65525. };
  65526. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  65527. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  65528. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  65529. // all animation may be coming from a library skeleton, so may need to create animation
  65530. if (this.animations.length === 0) {
  65531. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  65532. this.animations[0].setKeys([]);
  65533. }
  65534. // get animation info / verify there is such a range from the source bone
  65535. var sourceRange = source.animations[0].getRange(rangeName);
  65536. if (!sourceRange) {
  65537. return false;
  65538. }
  65539. var from = sourceRange.from;
  65540. var to = sourceRange.to;
  65541. var sourceKeys = source.animations[0].getKeys();
  65542. // rescaling prep
  65543. var sourceBoneLength = source.length;
  65544. var sourceParent = source.getParent();
  65545. var parent = this.getParent();
  65546. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  65547. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  65548. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  65549. var destKeys = this.animations[0].getKeys();
  65550. // loop vars declaration
  65551. var orig;
  65552. var origTranslation;
  65553. var mat;
  65554. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  65555. orig = sourceKeys[key];
  65556. if (orig.frame >= from && orig.frame <= to) {
  65557. if (rescaleAsRequired) {
  65558. mat = orig.value.clone();
  65559. // scale based on parent ratio, when bone has parent
  65560. if (parentScalingReqd) {
  65561. origTranslation = mat.getTranslation();
  65562. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  65563. // scale based on skeleton dimension ratio when root bone, and value is passed
  65564. }
  65565. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  65566. origTranslation = mat.getTranslation();
  65567. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  65568. // use original when root bone, and no data for skelDimensionsRatio
  65569. }
  65570. else {
  65571. mat = orig.value;
  65572. }
  65573. }
  65574. else {
  65575. mat = orig.value;
  65576. }
  65577. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  65578. }
  65579. }
  65580. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  65581. return true;
  65582. };
  65583. /**
  65584. * Translate the bone in local or world space.
  65585. * @param vec The amount to translate the bone.
  65586. * @param space The space that the translation is in.
  65587. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65588. */
  65589. Bone.prototype.translate = function (vec, space, mesh) {
  65590. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65591. var lm = this.getLocalMatrix();
  65592. if (space == BABYLON.Space.LOCAL) {
  65593. lm.m[12] += vec.x;
  65594. lm.m[13] += vec.y;
  65595. lm.m[14] += vec.z;
  65596. }
  65597. else {
  65598. var wm = null;
  65599. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  65600. if (mesh) {
  65601. wm = mesh.getWorldMatrix();
  65602. }
  65603. this._skeleton.computeAbsoluteTransforms();
  65604. var tmat = Bone._tmpMats[0];
  65605. var tvec = Bone._tmpVecs[0];
  65606. if (this._parent) {
  65607. if (mesh && wm) {
  65608. tmat.copyFrom(this._parent.getAbsoluteTransform());
  65609. tmat.multiplyToRef(wm, tmat);
  65610. }
  65611. else {
  65612. tmat.copyFrom(this._parent.getAbsoluteTransform());
  65613. }
  65614. }
  65615. tmat.m[12] = 0;
  65616. tmat.m[13] = 0;
  65617. tmat.m[14] = 0;
  65618. tmat.invert();
  65619. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  65620. lm.m[12] += tvec.x;
  65621. lm.m[13] += tvec.y;
  65622. lm.m[14] += tvec.z;
  65623. }
  65624. this.markAsDirty();
  65625. };
  65626. /**
  65627. * Set the postion of the bone in local or world space.
  65628. * @param position The position to set the bone.
  65629. * @param space The space that the position is in.
  65630. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65631. */
  65632. Bone.prototype.setPosition = function (position, space, mesh) {
  65633. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65634. var lm = this.getLocalMatrix();
  65635. if (space == BABYLON.Space.LOCAL) {
  65636. lm.m[12] = position.x;
  65637. lm.m[13] = position.y;
  65638. lm.m[14] = position.z;
  65639. }
  65640. else {
  65641. var wm = null;
  65642. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  65643. if (mesh) {
  65644. wm = mesh.getWorldMatrix();
  65645. }
  65646. this._skeleton.computeAbsoluteTransforms();
  65647. var tmat = Bone._tmpMats[0];
  65648. var vec = Bone._tmpVecs[0];
  65649. if (this._parent) {
  65650. if (mesh && wm) {
  65651. tmat.copyFrom(this._parent.getAbsoluteTransform());
  65652. tmat.multiplyToRef(wm, tmat);
  65653. }
  65654. else {
  65655. tmat.copyFrom(this._parent.getAbsoluteTransform());
  65656. }
  65657. }
  65658. tmat.invert();
  65659. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  65660. lm.m[12] = vec.x;
  65661. lm.m[13] = vec.y;
  65662. lm.m[14] = vec.z;
  65663. }
  65664. this.markAsDirty();
  65665. };
  65666. /**
  65667. * Set the absolute postion of the bone (world space).
  65668. * @param position The position to set the bone.
  65669. * @param mesh The mesh that this bone is attached to.
  65670. */
  65671. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  65672. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  65673. };
  65674. /**
  65675. * Set the scale of the bone on the x, y and z axes.
  65676. * @param x The scale of the bone on the x axis.
  65677. * @param x The scale of the bone on the y axis.
  65678. * @param z The scale of the bone on the z axis.
  65679. * @param scaleChildren Set this to true if children of the bone should be scaled.
  65680. */
  65681. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  65682. if (scaleChildren === void 0) { scaleChildren = false; }
  65683. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  65684. if (!scaleChildren) {
  65685. this._negateScaleChildren.x = 1 / x;
  65686. this._negateScaleChildren.y = 1 / y;
  65687. this._negateScaleChildren.z = 1 / z;
  65688. }
  65689. this._syncScaleVector();
  65690. }
  65691. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  65692. };
  65693. /**
  65694. * Scale the bone on the x, y and z axes.
  65695. * @param x The amount to scale the bone on the x axis.
  65696. * @param x The amount to scale the bone on the y axis.
  65697. * @param z The amount to scale the bone on the z axis.
  65698. * @param scaleChildren Set this to true if children of the bone should be scaled.
  65699. */
  65700. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  65701. if (scaleChildren === void 0) { scaleChildren = false; }
  65702. var locMat = this.getLocalMatrix();
  65703. var origLocMat = Bone._tmpMats[0];
  65704. origLocMat.copyFrom(locMat);
  65705. var origLocMatInv = Bone._tmpMats[1];
  65706. origLocMatInv.copyFrom(origLocMat);
  65707. origLocMatInv.invert();
  65708. var scaleMat = Bone._tmpMats[2];
  65709. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  65710. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  65711. this._scaleVector.x *= x;
  65712. this._scaleVector.y *= y;
  65713. this._scaleVector.z *= z;
  65714. locMat.multiplyToRef(origLocMatInv, locMat);
  65715. locMat.multiplyToRef(scaleMat, locMat);
  65716. locMat.multiplyToRef(origLocMat, locMat);
  65717. var parent = this.getParent();
  65718. if (parent) {
  65719. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  65720. }
  65721. else {
  65722. this.getAbsoluteTransform().copyFrom(locMat);
  65723. }
  65724. var len = this.children.length;
  65725. scaleMat.invert();
  65726. for (var i = 0; i < len; i++) {
  65727. var child = this.children[i];
  65728. var cm = child.getLocalMatrix();
  65729. cm.multiplyToRef(scaleMat, cm);
  65730. var lm = child.getLocalMatrix();
  65731. lm.m[12] *= x;
  65732. lm.m[13] *= y;
  65733. lm.m[14] *= z;
  65734. }
  65735. this.computeAbsoluteTransforms();
  65736. if (scaleChildren) {
  65737. for (var i = 0; i < len; i++) {
  65738. this.children[i].scale(x, y, z, scaleChildren);
  65739. }
  65740. }
  65741. this.markAsDirty();
  65742. };
  65743. /**
  65744. * Set the yaw, pitch, and roll of the bone in local or world space.
  65745. * @param yaw The rotation of the bone on the y axis.
  65746. * @param pitch The rotation of the bone on the x axis.
  65747. * @param roll The rotation of the bone on the z axis.
  65748. * @param space The space that the axes of rotation are in.
  65749. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65750. */
  65751. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  65752. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65753. var rotMat = Bone._tmpMats[0];
  65754. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  65755. var rotMatInv = Bone._tmpMats[1];
  65756. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  65757. rotMatInv.multiplyToRef(rotMat, rotMat);
  65758. this._rotateWithMatrix(rotMat, space, mesh);
  65759. };
  65760. /**
  65761. * Rotate the bone on an axis in local or world space.
  65762. * @param axis The axis to rotate the bone on.
  65763. * @param amount The amount to rotate the bone.
  65764. * @param space The space that the axis is in.
  65765. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65766. */
  65767. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  65768. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65769. var rmat = Bone._tmpMats[0];
  65770. rmat.m[12] = 0;
  65771. rmat.m[13] = 0;
  65772. rmat.m[14] = 0;
  65773. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  65774. this._rotateWithMatrix(rmat, space, mesh);
  65775. };
  65776. /**
  65777. * Set the rotation of the bone to a particular axis angle in local or world space.
  65778. * @param axis The axis to rotate the bone on.
  65779. * @param angle The angle that the bone should be rotated to.
  65780. * @param space The space that the axis is in.
  65781. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65782. */
  65783. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  65784. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65785. var rotMat = Bone._tmpMats[0];
  65786. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  65787. var rotMatInv = Bone._tmpMats[1];
  65788. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  65789. rotMatInv.multiplyToRef(rotMat, rotMat);
  65790. this._rotateWithMatrix(rotMat, space, mesh);
  65791. };
  65792. /**
  65793. * Set the euler rotation of the bone in local of world space.
  65794. * @param rotation The euler rotation that the bone should be set to.
  65795. * @param space The space that the rotation is in.
  65796. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65797. */
  65798. Bone.prototype.setRotation = function (rotation, space, mesh) {
  65799. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65800. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  65801. };
  65802. /**
  65803. * Set the quaternion rotation of the bone in local of world space.
  65804. * @param quat The quaternion rotation that the bone should be set to.
  65805. * @param space The space that the rotation is in.
  65806. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65807. */
  65808. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  65809. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65810. var rotMatInv = Bone._tmpMats[0];
  65811. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  65812. var rotMat = Bone._tmpMats[1];
  65813. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  65814. rotMatInv.multiplyToRef(rotMat, rotMat);
  65815. this._rotateWithMatrix(rotMat, space, mesh);
  65816. };
  65817. /**
  65818. * Set the rotation matrix of the bone in local of world space.
  65819. * @param rotMat The rotation matrix that the bone should be set to.
  65820. * @param space The space that the rotation is in.
  65821. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65822. */
  65823. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  65824. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65825. var rotMatInv = Bone._tmpMats[0];
  65826. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  65827. var rotMat2 = Bone._tmpMats[1];
  65828. rotMat2.copyFrom(rotMat);
  65829. rotMatInv.multiplyToRef(rotMat, rotMat2);
  65830. this._rotateWithMatrix(rotMat2, space, mesh);
  65831. };
  65832. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  65833. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65834. var lmat = this.getLocalMatrix();
  65835. var lx = lmat.m[12];
  65836. var ly = lmat.m[13];
  65837. var lz = lmat.m[14];
  65838. var parent = this.getParent();
  65839. var parentScale = Bone._tmpMats[3];
  65840. var parentScaleInv = Bone._tmpMats[4];
  65841. if (parent) {
  65842. if (space == BABYLON.Space.WORLD) {
  65843. if (mesh) {
  65844. parentScale.copyFrom(mesh.getWorldMatrix());
  65845. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  65846. }
  65847. else {
  65848. parentScale.copyFrom(parent.getAbsoluteTransform());
  65849. }
  65850. }
  65851. else {
  65852. parentScale = parent._scaleMatrix;
  65853. }
  65854. parentScaleInv.copyFrom(parentScale);
  65855. parentScaleInv.invert();
  65856. lmat.multiplyToRef(parentScale, lmat);
  65857. lmat.multiplyToRef(rmat, lmat);
  65858. lmat.multiplyToRef(parentScaleInv, lmat);
  65859. }
  65860. else {
  65861. if (space == BABYLON.Space.WORLD && mesh) {
  65862. parentScale.copyFrom(mesh.getWorldMatrix());
  65863. parentScaleInv.copyFrom(parentScale);
  65864. parentScaleInv.invert();
  65865. lmat.multiplyToRef(parentScale, lmat);
  65866. lmat.multiplyToRef(rmat, lmat);
  65867. lmat.multiplyToRef(parentScaleInv, lmat);
  65868. }
  65869. else {
  65870. lmat.multiplyToRef(rmat, lmat);
  65871. }
  65872. }
  65873. lmat.m[12] = lx;
  65874. lmat.m[13] = ly;
  65875. lmat.m[14] = lz;
  65876. this.computeAbsoluteTransforms();
  65877. this.markAsDirty();
  65878. };
  65879. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  65880. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65881. if (space == BABYLON.Space.WORLD) {
  65882. var scaleMatrix = Bone._tmpMats[2];
  65883. scaleMatrix.copyFrom(this._scaleMatrix);
  65884. rotMatInv.copyFrom(this.getAbsoluteTransform());
  65885. if (mesh) {
  65886. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  65887. var meshScale = Bone._tmpMats[3];
  65888. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  65889. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  65890. }
  65891. rotMatInv.invert();
  65892. scaleMatrix.m[0] *= this._scalingDeterminant;
  65893. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  65894. }
  65895. else {
  65896. rotMatInv.copyFrom(this.getLocalMatrix());
  65897. rotMatInv.invert();
  65898. var scaleMatrix = Bone._tmpMats[2];
  65899. scaleMatrix.copyFrom(this._scaleMatrix);
  65900. if (this._parent) {
  65901. var pscaleMatrix = Bone._tmpMats[3];
  65902. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  65903. pscaleMatrix.invert();
  65904. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  65905. }
  65906. else {
  65907. scaleMatrix.m[0] *= this._scalingDeterminant;
  65908. }
  65909. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  65910. }
  65911. };
  65912. /**
  65913. * Get the scale of the bone
  65914. * @returns the scale of the bone
  65915. */
  65916. Bone.prototype.getScale = function () {
  65917. return this._scaleVector.clone();
  65918. };
  65919. /**
  65920. * Copy the scale of the bone to a vector3.
  65921. * @param result The vector3 to copy the scale to
  65922. */
  65923. Bone.prototype.getScaleToRef = function (result) {
  65924. result.copyFrom(this._scaleVector);
  65925. };
  65926. /**
  65927. * Get the position of the bone in local or world space.
  65928. * @param space The space that the returned position is in.
  65929. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65930. * @returns The position of the bone
  65931. */
  65932. Bone.prototype.getPosition = function (space, mesh) {
  65933. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65934. if (mesh === void 0) { mesh = null; }
  65935. var pos = BABYLON.Vector3.Zero();
  65936. this.getPositionToRef(space, mesh, pos);
  65937. return pos;
  65938. };
  65939. /**
  65940. * Copy the position of the bone to a vector3 in local or world space.
  65941. * @param space The space that the returned position is in.
  65942. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65943. * @param result The vector3 to copy the position to.
  65944. */
  65945. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  65946. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65947. if (space == BABYLON.Space.LOCAL) {
  65948. var lm = this.getLocalMatrix();
  65949. result.x = lm.m[12];
  65950. result.y = lm.m[13];
  65951. result.z = lm.m[14];
  65952. }
  65953. else {
  65954. var wm = null;
  65955. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  65956. if (mesh) {
  65957. wm = mesh.getWorldMatrix();
  65958. }
  65959. this._skeleton.computeAbsoluteTransforms();
  65960. var tmat = Bone._tmpMats[0];
  65961. if (mesh && wm) {
  65962. tmat.copyFrom(this.getAbsoluteTransform());
  65963. tmat.multiplyToRef(wm, tmat);
  65964. }
  65965. else {
  65966. tmat = this.getAbsoluteTransform();
  65967. }
  65968. result.x = tmat.m[12];
  65969. result.y = tmat.m[13];
  65970. result.z = tmat.m[14];
  65971. }
  65972. };
  65973. /**
  65974. * Get the absolute position of the bone (world space).
  65975. * @param mesh The mesh that this bone is attached to.
  65976. * @returns The absolute position of the bone
  65977. */
  65978. Bone.prototype.getAbsolutePosition = function (mesh) {
  65979. if (mesh === void 0) { mesh = null; }
  65980. var pos = BABYLON.Vector3.Zero();
  65981. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  65982. return pos;
  65983. };
  65984. /**
  65985. * Copy the absolute position of the bone (world space) to the result param.
  65986. * @param mesh The mesh that this bone is attached to.
  65987. * @param result The vector3 to copy the absolute position to.
  65988. */
  65989. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  65990. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  65991. };
  65992. /**
  65993. * Compute the absolute transforms of this bone and its children.
  65994. */
  65995. Bone.prototype.computeAbsoluteTransforms = function () {
  65996. if (this._parent) {
  65997. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  65998. }
  65999. else {
  66000. this._absoluteTransform.copyFrom(this._localMatrix);
  66001. var poseMatrix = this._skeleton.getPoseMatrix();
  66002. if (poseMatrix) {
  66003. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  66004. }
  66005. }
  66006. var children = this.children;
  66007. var len = children.length;
  66008. for (var i = 0; i < len; i++) {
  66009. children[i].computeAbsoluteTransforms();
  66010. }
  66011. };
  66012. Bone.prototype._syncScaleVector = function () {
  66013. var lm = this.getLocalMatrix();
  66014. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  66015. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  66016. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  66017. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  66018. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  66019. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  66020. this._scaleVector.x = xs * Math.sqrt(xsq);
  66021. this._scaleVector.y = ys * Math.sqrt(ysq);
  66022. this._scaleVector.z = zs * Math.sqrt(zsq);
  66023. if (this._parent) {
  66024. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  66025. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  66026. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  66027. }
  66028. 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);
  66029. };
  66030. /**
  66031. * Get the world direction from an axis that is in the local space of the bone.
  66032. * @param localAxis The local direction that is used to compute the world direction.
  66033. * @param mesh The mesh that this bone is attached to.
  66034. * @returns The world direction
  66035. */
  66036. Bone.prototype.getDirection = function (localAxis, mesh) {
  66037. if (mesh === void 0) { mesh = null; }
  66038. var result = BABYLON.Vector3.Zero();
  66039. this.getDirectionToRef(localAxis, mesh, result);
  66040. return result;
  66041. };
  66042. /**
  66043. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  66044. * @param localAxis The local direction that is used to compute the world direction.
  66045. * @param mesh The mesh that this bone is attached to.
  66046. * @param result The vector3 that the world direction will be copied to.
  66047. */
  66048. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  66049. if (mesh === void 0) { mesh = null; }
  66050. var wm = null;
  66051. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  66052. if (mesh) {
  66053. wm = mesh.getWorldMatrix();
  66054. }
  66055. this._skeleton.computeAbsoluteTransforms();
  66056. var mat = Bone._tmpMats[0];
  66057. mat.copyFrom(this.getAbsoluteTransform());
  66058. if (mesh && wm) {
  66059. mat.multiplyToRef(wm, mat);
  66060. }
  66061. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  66062. result.normalize();
  66063. };
  66064. /**
  66065. * Get the euler rotation of the bone in local or world space.
  66066. * @param space The space that the rotation should be in.
  66067. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66068. * @returns The euler rotation
  66069. */
  66070. Bone.prototype.getRotation = function (space, mesh) {
  66071. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66072. if (mesh === void 0) { mesh = null; }
  66073. var result = BABYLON.Vector3.Zero();
  66074. this.getRotationToRef(space, mesh, result);
  66075. return result;
  66076. };
  66077. /**
  66078. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  66079. * @param space The space that the rotation should be in.
  66080. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66081. * @param result The vector3 that the rotation should be copied to.
  66082. */
  66083. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  66084. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66085. if (mesh === void 0) { mesh = null; }
  66086. var quat = Bone._tmpQuat;
  66087. this.getRotationQuaternionToRef(space, mesh, quat);
  66088. quat.toEulerAnglesToRef(result);
  66089. };
  66090. /**
  66091. * Get the quaternion rotation of the bone in either local or world space.
  66092. * @param space The space that the rotation should be in.
  66093. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66094. * @returns The quaternion rotation
  66095. */
  66096. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  66097. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66098. if (mesh === void 0) { mesh = null; }
  66099. var result = BABYLON.Quaternion.Identity();
  66100. this.getRotationQuaternionToRef(space, mesh, result);
  66101. return result;
  66102. };
  66103. /**
  66104. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  66105. * @param space The space that the rotation should be in.
  66106. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66107. * @param result The quaternion that the rotation should be copied to.
  66108. */
  66109. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  66110. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66111. if (mesh === void 0) { mesh = null; }
  66112. if (space == BABYLON.Space.LOCAL) {
  66113. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  66114. }
  66115. else {
  66116. var mat = Bone._tmpMats[0];
  66117. var amat = this.getAbsoluteTransform();
  66118. if (mesh) {
  66119. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  66120. }
  66121. else {
  66122. mat.copyFrom(amat);
  66123. }
  66124. mat.m[0] *= this._scalingDeterminant;
  66125. mat.m[1] *= this._scalingDeterminant;
  66126. mat.m[2] *= this._scalingDeterminant;
  66127. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  66128. }
  66129. };
  66130. /**
  66131. * Get the rotation matrix of the bone in local or world space.
  66132. * @param space The space that the rotation should be in.
  66133. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66134. * @returns The rotation matrix
  66135. */
  66136. Bone.prototype.getRotationMatrix = function (space, mesh) {
  66137. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66138. var result = BABYLON.Matrix.Identity();
  66139. this.getRotationMatrixToRef(space, mesh, result);
  66140. return result;
  66141. };
  66142. /**
  66143. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  66144. * @param space The space that the rotation should be in.
  66145. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66146. * @param result The quaternion that the rotation should be copied to.
  66147. */
  66148. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  66149. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66150. if (space == BABYLON.Space.LOCAL) {
  66151. this.getLocalMatrix().getRotationMatrixToRef(result);
  66152. }
  66153. else {
  66154. var mat = Bone._tmpMats[0];
  66155. var amat = this.getAbsoluteTransform();
  66156. if (mesh) {
  66157. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  66158. }
  66159. else {
  66160. mat.copyFrom(amat);
  66161. }
  66162. mat.m[0] *= this._scalingDeterminant;
  66163. mat.m[1] *= this._scalingDeterminant;
  66164. mat.m[2] *= this._scalingDeterminant;
  66165. mat.getRotationMatrixToRef(result);
  66166. }
  66167. };
  66168. /**
  66169. * Get the world position of a point that is in the local space of the bone.
  66170. * @param position The local position
  66171. * @param mesh The mesh that this bone is attached to.
  66172. * @returns The world position
  66173. */
  66174. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  66175. if (mesh === void 0) { mesh = null; }
  66176. var result = BABYLON.Vector3.Zero();
  66177. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  66178. return result;
  66179. };
  66180. /**
  66181. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  66182. * @param position The local position
  66183. * @param mesh The mesh that this bone is attached to.
  66184. * @param result The vector3 that the world position should be copied to.
  66185. */
  66186. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  66187. if (mesh === void 0) { mesh = null; }
  66188. var wm = null;
  66189. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  66190. if (mesh) {
  66191. wm = mesh.getWorldMatrix();
  66192. }
  66193. this._skeleton.computeAbsoluteTransforms();
  66194. var tmat = Bone._tmpMats[0];
  66195. if (mesh && wm) {
  66196. tmat.copyFrom(this.getAbsoluteTransform());
  66197. tmat.multiplyToRef(wm, tmat);
  66198. }
  66199. else {
  66200. tmat = this.getAbsoluteTransform();
  66201. }
  66202. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  66203. };
  66204. /**
  66205. * Get the local position of a point that is in world space.
  66206. * @param position The world position
  66207. * @param mesh The mesh that this bone is attached to.
  66208. * @returns The local position
  66209. */
  66210. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  66211. if (mesh === void 0) { mesh = null; }
  66212. var result = BABYLON.Vector3.Zero();
  66213. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  66214. return result;
  66215. };
  66216. /**
  66217. * Get the local position of a point that is in world space and copy it to the result param.
  66218. * @param position The world position
  66219. * @param mesh The mesh that this bone is attached to.
  66220. * @param result The vector3 that the local position should be copied to.
  66221. */
  66222. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  66223. if (mesh === void 0) { mesh = null; }
  66224. var wm = null;
  66225. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  66226. if (mesh) {
  66227. wm = mesh.getWorldMatrix();
  66228. }
  66229. this._skeleton.computeAbsoluteTransforms();
  66230. var tmat = Bone._tmpMats[0];
  66231. tmat.copyFrom(this.getAbsoluteTransform());
  66232. if (mesh && wm) {
  66233. tmat.multiplyToRef(wm, tmat);
  66234. }
  66235. tmat.invert();
  66236. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  66237. };
  66238. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  66239. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  66240. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  66241. return Bone;
  66242. }(BABYLON.Node));
  66243. BABYLON.Bone = Bone;
  66244. })(BABYLON || (BABYLON = {}));
  66245. //# sourceMappingURL=babylon.bone.js.map
  66246. var BABYLON;
  66247. (function (BABYLON) {
  66248. var BoneIKController = /** @class */ (function () {
  66249. function BoneIKController(mesh, bone, options) {
  66250. this.targetPosition = BABYLON.Vector3.Zero();
  66251. this.poleTargetPosition = BABYLON.Vector3.Zero();
  66252. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  66253. this.poleAngle = 0;
  66254. this.slerpAmount = 1;
  66255. this._bone1Quat = BABYLON.Quaternion.Identity();
  66256. this._bone1Mat = BABYLON.Matrix.Identity();
  66257. this._bone2Ang = Math.PI;
  66258. this._maxAngle = Math.PI;
  66259. this._rightHandedSystem = false;
  66260. this._bendAxis = BABYLON.Vector3.Right();
  66261. this._slerping = false;
  66262. this._adjustRoll = 0;
  66263. this._bone2 = bone;
  66264. this._bone1 = bone.getParent();
  66265. if (!this._bone1) {
  66266. return;
  66267. }
  66268. this.mesh = mesh;
  66269. var bonePos = bone.getPosition();
  66270. if (bone.getAbsoluteTransform().determinant() > 0) {
  66271. this._rightHandedSystem = true;
  66272. this._bendAxis.x = 0;
  66273. this._bendAxis.y = 0;
  66274. this._bendAxis.z = -1;
  66275. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  66276. this._adjustRoll = Math.PI * .5;
  66277. this._bendAxis.z = 1;
  66278. }
  66279. }
  66280. if (this._bone1.length) {
  66281. var boneScale1 = this._bone1.getScale();
  66282. var boneScale2 = this._bone2.getScale();
  66283. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  66284. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  66285. }
  66286. else if (this._bone1.children[0]) {
  66287. mesh.computeWorldMatrix(true);
  66288. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  66289. var pos2 = this._bone2.getAbsolutePosition(mesh);
  66290. var pos3 = this._bone1.getAbsolutePosition(mesh);
  66291. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  66292. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  66293. }
  66294. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  66295. this.maxAngle = Math.PI;
  66296. if (options) {
  66297. if (options.targetMesh) {
  66298. this.targetMesh = options.targetMesh;
  66299. this.targetMesh.computeWorldMatrix(true);
  66300. }
  66301. if (options.poleTargetMesh) {
  66302. this.poleTargetMesh = options.poleTargetMesh;
  66303. this.poleTargetMesh.computeWorldMatrix(true);
  66304. }
  66305. else if (options.poleTargetBone) {
  66306. this.poleTargetBone = options.poleTargetBone;
  66307. }
  66308. else if (this._bone1.getParent()) {
  66309. this.poleTargetBone = this._bone1.getParent();
  66310. }
  66311. if (options.poleTargetLocalOffset) {
  66312. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  66313. }
  66314. if (options.poleAngle) {
  66315. this.poleAngle = options.poleAngle;
  66316. }
  66317. if (options.bendAxis) {
  66318. this._bendAxis.copyFrom(options.bendAxis);
  66319. }
  66320. if (options.maxAngle) {
  66321. this.maxAngle = options.maxAngle;
  66322. }
  66323. if (options.slerpAmount) {
  66324. this.slerpAmount = options.slerpAmount;
  66325. }
  66326. }
  66327. }
  66328. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  66329. get: function () {
  66330. return this._maxAngle;
  66331. },
  66332. set: function (value) {
  66333. this._setMaxAngle(value);
  66334. },
  66335. enumerable: true,
  66336. configurable: true
  66337. });
  66338. BoneIKController.prototype._setMaxAngle = function (ang) {
  66339. if (ang < 0) {
  66340. ang = 0;
  66341. }
  66342. if (ang > Math.PI || ang == undefined) {
  66343. ang = Math.PI;
  66344. }
  66345. this._maxAngle = ang;
  66346. var a = this._bone1Length;
  66347. var b = this._bone2Length;
  66348. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  66349. };
  66350. BoneIKController.prototype.update = function () {
  66351. var bone1 = this._bone1;
  66352. if (!bone1) {
  66353. return;
  66354. }
  66355. var target = this.targetPosition;
  66356. var poleTarget = this.poleTargetPosition;
  66357. var mat1 = BoneIKController._tmpMats[0];
  66358. var mat2 = BoneIKController._tmpMats[1];
  66359. if (this.targetMesh) {
  66360. target.copyFrom(this.targetMesh.getAbsolutePosition());
  66361. }
  66362. if (this.poleTargetBone) {
  66363. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  66364. }
  66365. else if (this.poleTargetMesh) {
  66366. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  66367. }
  66368. var bonePos = BoneIKController._tmpVecs[0];
  66369. var zaxis = BoneIKController._tmpVecs[1];
  66370. var xaxis = BoneIKController._tmpVecs[2];
  66371. var yaxis = BoneIKController._tmpVecs[3];
  66372. var upAxis = BoneIKController._tmpVecs[4];
  66373. var _tmpQuat = BoneIKController._tmpQuat;
  66374. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  66375. poleTarget.subtractToRef(bonePos, upAxis);
  66376. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  66377. upAxis.y = 1;
  66378. }
  66379. else {
  66380. upAxis.normalize();
  66381. }
  66382. target.subtractToRef(bonePos, yaxis);
  66383. yaxis.normalize();
  66384. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  66385. zaxis.normalize();
  66386. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  66387. xaxis.normalize();
  66388. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  66389. var a = this._bone1Length;
  66390. var b = this._bone2Length;
  66391. var c = BABYLON.Vector3.Distance(bonePos, target);
  66392. if (this._maxReach > 0) {
  66393. c = Math.min(this._maxReach, c);
  66394. }
  66395. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  66396. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  66397. if (acosa > 1) {
  66398. acosa = 1;
  66399. }
  66400. if (acosb > 1) {
  66401. acosb = 1;
  66402. }
  66403. if (acosa < -1) {
  66404. acosa = -1;
  66405. }
  66406. if (acosb < -1) {
  66407. acosb = -1;
  66408. }
  66409. var angA = Math.acos(acosa);
  66410. var angB = Math.acos(acosb);
  66411. var angC = -angA - angB;
  66412. if (this._rightHandedSystem) {
  66413. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  66414. mat2.multiplyToRef(mat1, mat1);
  66415. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  66416. mat2.multiplyToRef(mat1, mat1);
  66417. }
  66418. else {
  66419. var _tmpVec = BoneIKController._tmpVecs[5];
  66420. _tmpVec.copyFrom(this._bendAxis);
  66421. _tmpVec.x *= -1;
  66422. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  66423. mat2.multiplyToRef(mat1, mat1);
  66424. }
  66425. if (this.poleAngle) {
  66426. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  66427. mat1.multiplyToRef(mat2, mat1);
  66428. }
  66429. if (this._bone1) {
  66430. if (this.slerpAmount < 1) {
  66431. if (!this._slerping) {
  66432. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  66433. }
  66434. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  66435. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  66436. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  66437. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  66438. this._slerping = true;
  66439. }
  66440. else {
  66441. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  66442. this._bone1Mat.copyFrom(mat1);
  66443. this._slerping = false;
  66444. }
  66445. }
  66446. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  66447. this._bone2Ang = angC;
  66448. };
  66449. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  66450. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  66451. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  66452. return BoneIKController;
  66453. }());
  66454. BABYLON.BoneIKController = BoneIKController;
  66455. })(BABYLON || (BABYLON = {}));
  66456. //# sourceMappingURL=babylon.boneIKController.js.map
  66457. var BABYLON;
  66458. (function (BABYLON) {
  66459. var BoneLookController = /** @class */ (function () {
  66460. /**
  66461. * Create a BoneLookController
  66462. * @param mesh the mesh that the bone belongs to
  66463. * @param bone the bone that will be looking to the target
  66464. * @param target the target Vector3 to look at
  66465. * @param settings optional settings:
  66466. * - maxYaw: the maximum angle the bone will yaw to
  66467. * - minYaw: the minimum angle the bone will yaw to
  66468. * - maxPitch: the maximum angle the bone will pitch to
  66469. * - minPitch: the minimum angle the bone will yaw to
  66470. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  66471. * - upAxis: the up axis of the coordinate system
  66472. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  66473. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  66474. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  66475. * - adjustYaw: used to make an adjustment to the yaw of the bone
  66476. * - adjustPitch: used to make an adjustment to the pitch of the bone
  66477. * - adjustRoll: used to make an adjustment to the roll of the bone
  66478. **/
  66479. function BoneLookController(mesh, bone, target, options) {
  66480. /**
  66481. * The up axis of the coordinate system that is used when the bone is rotated.
  66482. */
  66483. this.upAxis = BABYLON.Vector3.Up();
  66484. /**
  66485. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  66486. */
  66487. this.upAxisSpace = BABYLON.Space.LOCAL;
  66488. /**
  66489. * Used to make an adjustment to the yaw of the bone.
  66490. */
  66491. this.adjustYaw = 0;
  66492. /**
  66493. * Used to make an adjustment to the pitch of the bone.
  66494. */
  66495. this.adjustPitch = 0;
  66496. /**
  66497. * Used to make an adjustment to the roll of the bone.
  66498. */
  66499. this.adjustRoll = 0;
  66500. /**
  66501. * 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).
  66502. */
  66503. this.slerpAmount = 1;
  66504. this._boneQuat = BABYLON.Quaternion.Identity();
  66505. this._slerping = false;
  66506. this._firstFrameSkipped = false;
  66507. this._fowardAxis = BABYLON.Vector3.Forward();
  66508. this.mesh = mesh;
  66509. this.bone = bone;
  66510. this.target = target;
  66511. if (options) {
  66512. if (options.adjustYaw) {
  66513. this.adjustYaw = options.adjustYaw;
  66514. }
  66515. if (options.adjustPitch) {
  66516. this.adjustPitch = options.adjustPitch;
  66517. }
  66518. if (options.adjustRoll) {
  66519. this.adjustRoll = options.adjustRoll;
  66520. }
  66521. if (options.maxYaw != null) {
  66522. this.maxYaw = options.maxYaw;
  66523. }
  66524. else {
  66525. this.maxYaw = Math.PI;
  66526. }
  66527. if (options.minYaw != null) {
  66528. this.minYaw = options.minYaw;
  66529. }
  66530. else {
  66531. this.minYaw = -Math.PI;
  66532. }
  66533. if (options.maxPitch != null) {
  66534. this.maxPitch = options.maxPitch;
  66535. }
  66536. else {
  66537. this.maxPitch = Math.PI;
  66538. }
  66539. if (options.minPitch != null) {
  66540. this.minPitch = options.minPitch;
  66541. }
  66542. else {
  66543. this.minPitch = -Math.PI;
  66544. }
  66545. if (options.slerpAmount != null) {
  66546. this.slerpAmount = options.slerpAmount;
  66547. }
  66548. if (options.upAxis != null) {
  66549. this.upAxis = options.upAxis;
  66550. }
  66551. if (options.upAxisSpace != null) {
  66552. this.upAxisSpace = options.upAxisSpace;
  66553. }
  66554. if (options.yawAxis != null || options.pitchAxis != null) {
  66555. var newYawAxis = BABYLON.Axis.Y;
  66556. var newPitchAxis = BABYLON.Axis.X;
  66557. if (options.yawAxis != null) {
  66558. newYawAxis = options.yawAxis.clone();
  66559. newYawAxis.normalize();
  66560. }
  66561. if (options.pitchAxis != null) {
  66562. newPitchAxis = options.pitchAxis.clone();
  66563. newPitchAxis.normalize();
  66564. }
  66565. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  66566. this._transformYawPitch = BABYLON.Matrix.Identity();
  66567. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  66568. this._transformYawPitchInv = this._transformYawPitch.clone();
  66569. this._transformYawPitch.invert();
  66570. }
  66571. }
  66572. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  66573. this.upAxisSpace = BABYLON.Space.LOCAL;
  66574. }
  66575. }
  66576. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  66577. /**
  66578. * Get/set the minimum yaw angle that the bone can look to.
  66579. */
  66580. get: function () {
  66581. return this._minYaw;
  66582. },
  66583. set: function (value) {
  66584. this._minYaw = value;
  66585. this._minYawSin = Math.sin(value);
  66586. this._minYawCos = Math.cos(value);
  66587. if (this._maxYaw != null) {
  66588. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  66589. this._yawRange = this._maxYaw - this._minYaw;
  66590. }
  66591. },
  66592. enumerable: true,
  66593. configurable: true
  66594. });
  66595. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  66596. /**
  66597. * Get/set the maximum yaw angle that the bone can look to.
  66598. */
  66599. get: function () {
  66600. return this._maxYaw;
  66601. },
  66602. set: function (value) {
  66603. this._maxYaw = value;
  66604. this._maxYawSin = Math.sin(value);
  66605. this._maxYawCos = Math.cos(value);
  66606. if (this._minYaw != null) {
  66607. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  66608. this._yawRange = this._maxYaw - this._minYaw;
  66609. }
  66610. },
  66611. enumerable: true,
  66612. configurable: true
  66613. });
  66614. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  66615. /**
  66616. * Get/set the minimum pitch angle that the bone can look to.
  66617. */
  66618. get: function () {
  66619. return this._minPitch;
  66620. },
  66621. set: function (value) {
  66622. this._minPitch = value;
  66623. this._minPitchTan = Math.tan(value);
  66624. },
  66625. enumerable: true,
  66626. configurable: true
  66627. });
  66628. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  66629. /**
  66630. * Get/set the maximum pitch angle that the bone can look to.
  66631. */
  66632. get: function () {
  66633. return this._maxPitch;
  66634. },
  66635. set: function (value) {
  66636. this._maxPitch = value;
  66637. this._maxPitchTan = Math.tan(value);
  66638. },
  66639. enumerable: true,
  66640. configurable: true
  66641. });
  66642. /**
  66643. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  66644. */
  66645. BoneLookController.prototype.update = function () {
  66646. //skip the first frame when slerping so that the mesh rotation is correct
  66647. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  66648. this._firstFrameSkipped = true;
  66649. return;
  66650. }
  66651. var bone = this.bone;
  66652. var bonePos = BoneLookController._tmpVecs[0];
  66653. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  66654. var target = this.target;
  66655. var _tmpMat1 = BoneLookController._tmpMats[0];
  66656. var _tmpMat2 = BoneLookController._tmpMats[1];
  66657. var mesh = this.mesh;
  66658. var parentBone = bone.getParent();
  66659. var upAxis = BoneLookController._tmpVecs[1];
  66660. upAxis.copyFrom(this.upAxis);
  66661. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  66662. if (this._transformYawPitch) {
  66663. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  66664. }
  66665. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  66666. }
  66667. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  66668. mesh.getDirectionToRef(upAxis, upAxis);
  66669. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  66670. upAxis.normalize();
  66671. }
  66672. }
  66673. var checkYaw = false;
  66674. var checkPitch = false;
  66675. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  66676. checkYaw = true;
  66677. }
  66678. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  66679. checkPitch = true;
  66680. }
  66681. if (checkYaw || checkPitch) {
  66682. var spaceMat = BoneLookController._tmpMats[2];
  66683. var spaceMatInv = BoneLookController._tmpMats[3];
  66684. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  66685. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  66686. }
  66687. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  66688. spaceMat.copyFrom(mesh.getWorldMatrix());
  66689. }
  66690. else {
  66691. var forwardAxis = BoneLookController._tmpVecs[2];
  66692. forwardAxis.copyFrom(this._fowardAxis);
  66693. if (this._transformYawPitch) {
  66694. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  66695. }
  66696. if (parentBone) {
  66697. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  66698. }
  66699. else {
  66700. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  66701. }
  66702. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  66703. rightAxis.normalize();
  66704. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  66705. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  66706. }
  66707. spaceMat.invertToRef(spaceMatInv);
  66708. var xzlen = null;
  66709. if (checkPitch) {
  66710. var localTarget = BoneLookController._tmpVecs[3];
  66711. target.subtractToRef(bonePos, localTarget);
  66712. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  66713. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  66714. var pitch = Math.atan2(localTarget.y, xzlen);
  66715. var newPitch = pitch;
  66716. if (pitch > this._maxPitch) {
  66717. localTarget.y = this._maxPitchTan * xzlen;
  66718. newPitch = this._maxPitch;
  66719. }
  66720. else if (pitch < this._minPitch) {
  66721. localTarget.y = this._minPitchTan * xzlen;
  66722. newPitch = this._minPitch;
  66723. }
  66724. if (pitch != newPitch) {
  66725. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  66726. localTarget.addInPlace(bonePos);
  66727. target = localTarget;
  66728. }
  66729. }
  66730. if (checkYaw) {
  66731. var localTarget = BoneLookController._tmpVecs[4];
  66732. target.subtractToRef(bonePos, localTarget);
  66733. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  66734. var yaw = Math.atan2(localTarget.x, localTarget.z);
  66735. var newYaw = yaw;
  66736. if (yaw > this._maxYaw || yaw < this._minYaw) {
  66737. if (xzlen == null) {
  66738. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  66739. }
  66740. if (this._yawRange > Math.PI) {
  66741. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  66742. localTarget.z = this._maxYawCos * xzlen;
  66743. localTarget.x = this._maxYawSin * xzlen;
  66744. newYaw = this._maxYaw;
  66745. }
  66746. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  66747. localTarget.z = this._minYawCos * xzlen;
  66748. localTarget.x = this._minYawSin * xzlen;
  66749. newYaw = this._minYaw;
  66750. }
  66751. }
  66752. else {
  66753. if (yaw > this._maxYaw) {
  66754. localTarget.z = this._maxYawCos * xzlen;
  66755. localTarget.x = this._maxYawSin * xzlen;
  66756. newYaw = this._maxYaw;
  66757. }
  66758. else if (yaw < this._minYaw) {
  66759. localTarget.z = this._minYawCos * xzlen;
  66760. localTarget.x = this._minYawSin * xzlen;
  66761. newYaw = this._minYaw;
  66762. }
  66763. }
  66764. }
  66765. if (this._slerping && this._yawRange > Math.PI) {
  66766. //are we going to be crossing into the min/max region?
  66767. var boneFwd = BoneLookController._tmpVecs[8];
  66768. boneFwd.copyFrom(BABYLON.Axis.Z);
  66769. if (this._transformYawPitch) {
  66770. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  66771. }
  66772. var boneRotMat = BoneLookController._tmpMats[4];
  66773. this._boneQuat.toRotationMatrix(boneRotMat);
  66774. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  66775. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  66776. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  66777. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  66778. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  66779. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  66780. if (angBtwTar > angBtwMidYaw) {
  66781. if (xzlen == null) {
  66782. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  66783. }
  66784. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  66785. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  66786. if (angBtwMin < angBtwMax) {
  66787. newYaw = boneYaw + Math.PI * .75;
  66788. localTarget.z = Math.cos(newYaw) * xzlen;
  66789. localTarget.x = Math.sin(newYaw) * xzlen;
  66790. }
  66791. else {
  66792. newYaw = boneYaw - Math.PI * .75;
  66793. localTarget.z = Math.cos(newYaw) * xzlen;
  66794. localTarget.x = Math.sin(newYaw) * xzlen;
  66795. }
  66796. }
  66797. }
  66798. if (yaw != newYaw) {
  66799. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  66800. localTarget.addInPlace(bonePos);
  66801. target = localTarget;
  66802. }
  66803. }
  66804. }
  66805. var zaxis = BoneLookController._tmpVecs[5];
  66806. var xaxis = BoneLookController._tmpVecs[6];
  66807. var yaxis = BoneLookController._tmpVecs[7];
  66808. var _tmpQuat = BoneLookController._tmpQuat;
  66809. target.subtractToRef(bonePos, zaxis);
  66810. zaxis.normalize();
  66811. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  66812. xaxis.normalize();
  66813. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  66814. yaxis.normalize();
  66815. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  66816. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  66817. return;
  66818. }
  66819. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  66820. return;
  66821. }
  66822. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  66823. return;
  66824. }
  66825. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  66826. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  66827. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  66828. }
  66829. if (this.slerpAmount < 1) {
  66830. if (!this._slerping) {
  66831. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  66832. }
  66833. if (this._transformYawPitch) {
  66834. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  66835. }
  66836. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  66837. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  66838. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  66839. this._slerping = true;
  66840. }
  66841. else {
  66842. if (this._transformYawPitch) {
  66843. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  66844. }
  66845. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  66846. this._slerping = false;
  66847. }
  66848. };
  66849. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  66850. var angDiff = ang2 - ang1;
  66851. angDiff %= Math.PI * 2;
  66852. if (angDiff > Math.PI) {
  66853. angDiff -= Math.PI * 2;
  66854. }
  66855. else if (angDiff < -Math.PI) {
  66856. angDiff += Math.PI * 2;
  66857. }
  66858. return angDiff;
  66859. };
  66860. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  66861. ang1 %= (2 * Math.PI);
  66862. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  66863. ang2 %= (2 * Math.PI);
  66864. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  66865. var ab = 0;
  66866. if (ang1 < ang2) {
  66867. ab = ang2 - ang1;
  66868. }
  66869. else {
  66870. ab = ang1 - ang2;
  66871. }
  66872. if (ab > Math.PI) {
  66873. ab = Math.PI * 2 - ab;
  66874. }
  66875. return ab;
  66876. };
  66877. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  66878. ang %= (2 * Math.PI);
  66879. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  66880. ang1 %= (2 * Math.PI);
  66881. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  66882. ang2 %= (2 * Math.PI);
  66883. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  66884. if (ang1 < ang2) {
  66885. if (ang > ang1 && ang < ang2) {
  66886. return true;
  66887. }
  66888. }
  66889. else {
  66890. if (ang > ang2 && ang < ang1) {
  66891. return true;
  66892. }
  66893. }
  66894. return false;
  66895. };
  66896. 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()];
  66897. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  66898. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  66899. return BoneLookController;
  66900. }());
  66901. BABYLON.BoneLookController = BoneLookController;
  66902. })(BABYLON || (BABYLON = {}));
  66903. //# sourceMappingURL=babylon.boneLookController.js.map
  66904. var BABYLON;
  66905. (function (BABYLON) {
  66906. var Skeleton = /** @class */ (function () {
  66907. function Skeleton(name, id, scene) {
  66908. this.name = name;
  66909. this.id = id;
  66910. this.bones = new Array();
  66911. this.needInitialSkinMatrix = false;
  66912. this._isDirty = true;
  66913. this._meshesWithPoseMatrix = new Array();
  66914. this._identity = BABYLON.Matrix.Identity();
  66915. this._ranges = {};
  66916. this._lastAbsoluteTransformsUpdateId = -1;
  66917. // Events
  66918. /**
  66919. * An event triggered before computing the skeleton's matrices
  66920. * @type {BABYLON.Observable}
  66921. */
  66922. this.onBeforeComputeObservable = new BABYLON.Observable();
  66923. this.bones = [];
  66924. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  66925. scene.skeletons.push(this);
  66926. //make sure it will recalculate the matrix next time prepare is called.
  66927. this._isDirty = true;
  66928. }
  66929. // Members
  66930. Skeleton.prototype.getTransformMatrices = function (mesh) {
  66931. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  66932. return mesh._bonesTransformMatrices;
  66933. }
  66934. if (!this._transformMatrices) {
  66935. this.prepare();
  66936. }
  66937. return this._transformMatrices;
  66938. };
  66939. Skeleton.prototype.getScene = function () {
  66940. return this._scene;
  66941. };
  66942. // Methods
  66943. /**
  66944. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  66945. */
  66946. Skeleton.prototype.toString = function (fullDetails) {
  66947. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  66948. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  66949. if (fullDetails) {
  66950. ret += ", Ranges: {";
  66951. var first = true;
  66952. for (var name_1 in this._ranges) {
  66953. if (first) {
  66954. ret += ", ";
  66955. first = false;
  66956. }
  66957. ret += name_1;
  66958. }
  66959. ret += "}";
  66960. }
  66961. return ret;
  66962. };
  66963. /**
  66964. * Get bone's index searching by name
  66965. * @param {string} name is bone's name to search for
  66966. * @return {number} Indice of the bone. Returns -1 if not found
  66967. */
  66968. Skeleton.prototype.getBoneIndexByName = function (name) {
  66969. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  66970. if (this.bones[boneIndex].name === name) {
  66971. return boneIndex;
  66972. }
  66973. }
  66974. return -1;
  66975. };
  66976. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  66977. // check name not already in use
  66978. if (!this._ranges[name]) {
  66979. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  66980. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  66981. if (this.bones[i].animations[0]) {
  66982. this.bones[i].animations[0].createRange(name, from, to);
  66983. }
  66984. }
  66985. }
  66986. };
  66987. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  66988. if (deleteFrames === void 0) { deleteFrames = true; }
  66989. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  66990. if (this.bones[i].animations[0]) {
  66991. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  66992. }
  66993. }
  66994. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  66995. };
  66996. Skeleton.prototype.getAnimationRange = function (name) {
  66997. return this._ranges[name];
  66998. };
  66999. /**
  67000. * Returns as an Array, all AnimationRanges defined on this skeleton
  67001. */
  67002. Skeleton.prototype.getAnimationRanges = function () {
  67003. var animationRanges = [];
  67004. var name;
  67005. var i = 0;
  67006. for (name in this._ranges) {
  67007. animationRanges[i] = this._ranges[name];
  67008. i++;
  67009. }
  67010. return animationRanges;
  67011. };
  67012. /**
  67013. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  67014. */
  67015. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  67016. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  67017. if (this._ranges[name] || !source.getAnimationRange(name)) {
  67018. return false;
  67019. }
  67020. var ret = true;
  67021. var frameOffset = this._getHighestAnimationFrame() + 1;
  67022. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  67023. var boneDict = {};
  67024. var sourceBones = source.bones;
  67025. var nBones;
  67026. var i;
  67027. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  67028. boneDict[sourceBones[i].name] = sourceBones[i];
  67029. }
  67030. if (this.bones.length !== sourceBones.length) {
  67031. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  67032. ret = false;
  67033. }
  67034. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  67035. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  67036. var boneName = this.bones[i].name;
  67037. var sourceBone = boneDict[boneName];
  67038. if (sourceBone) {
  67039. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  67040. }
  67041. else {
  67042. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  67043. ret = false;
  67044. }
  67045. }
  67046. // do not call createAnimationRange(), since it also is done to bones, which was already done
  67047. var range = source.getAnimationRange(name);
  67048. if (range) {
  67049. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  67050. }
  67051. return ret;
  67052. };
  67053. Skeleton.prototype.returnToRest = function () {
  67054. for (var index = 0; index < this.bones.length; index++) {
  67055. this.bones[index].returnToRest();
  67056. }
  67057. };
  67058. Skeleton.prototype._getHighestAnimationFrame = function () {
  67059. var ret = 0;
  67060. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  67061. if (this.bones[i].animations[0]) {
  67062. var highest = this.bones[i].animations[0].getHighestFrame();
  67063. if (ret < highest) {
  67064. ret = highest;
  67065. }
  67066. }
  67067. }
  67068. return ret;
  67069. };
  67070. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  67071. var range = this.getAnimationRange(name);
  67072. if (!range) {
  67073. return null;
  67074. }
  67075. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  67076. };
  67077. Skeleton.prototype._markAsDirty = function () {
  67078. this._isDirty = true;
  67079. };
  67080. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  67081. this._meshesWithPoseMatrix.push(mesh);
  67082. };
  67083. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  67084. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  67085. if (index > -1) {
  67086. this._meshesWithPoseMatrix.splice(index, 1);
  67087. }
  67088. };
  67089. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  67090. this.onBeforeComputeObservable.notifyObservers(this);
  67091. for (var index = 0; index < this.bones.length; index++) {
  67092. var bone = this.bones[index];
  67093. var parentBone = bone.getParent();
  67094. if (parentBone) {
  67095. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  67096. }
  67097. else {
  67098. if (initialSkinMatrix) {
  67099. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  67100. }
  67101. else {
  67102. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  67103. }
  67104. }
  67105. if (bone._index !== -1) {
  67106. var mappedIndex = bone._index === null ? index : bone._index;
  67107. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  67108. }
  67109. }
  67110. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  67111. };
  67112. Skeleton.prototype.prepare = function () {
  67113. if (!this._isDirty) {
  67114. return;
  67115. }
  67116. if (this.needInitialSkinMatrix) {
  67117. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  67118. var mesh = this._meshesWithPoseMatrix[index];
  67119. var poseMatrix = mesh.getPoseMatrix();
  67120. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  67121. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  67122. }
  67123. if (this._synchronizedWithMesh !== mesh) {
  67124. this._synchronizedWithMesh = mesh;
  67125. // Prepare bones
  67126. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  67127. var bone = this.bones[boneIndex];
  67128. if (!bone.getParent()) {
  67129. var matrix = bone.getBaseMatrix();
  67130. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  67131. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  67132. }
  67133. }
  67134. }
  67135. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  67136. }
  67137. }
  67138. else {
  67139. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  67140. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  67141. }
  67142. this._computeTransformMatrices(this._transformMatrices, null);
  67143. }
  67144. this._isDirty = false;
  67145. this._scene._activeBones.addCount(this.bones.length, false);
  67146. };
  67147. Skeleton.prototype.getAnimatables = function () {
  67148. if (!this._animatables || this._animatables.length !== this.bones.length) {
  67149. this._animatables = [];
  67150. for (var index = 0; index < this.bones.length; index++) {
  67151. this._animatables.push(this.bones[index]);
  67152. }
  67153. }
  67154. return this._animatables;
  67155. };
  67156. Skeleton.prototype.clone = function (name, id) {
  67157. var result = new Skeleton(name, id || name, this._scene);
  67158. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  67159. for (var index = 0; index < this.bones.length; index++) {
  67160. var source = this.bones[index];
  67161. var parentBone = null;
  67162. var parent_1 = source.getParent();
  67163. if (parent_1) {
  67164. var parentIndex = this.bones.indexOf(parent_1);
  67165. parentBone = result.bones[parentIndex];
  67166. }
  67167. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  67168. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  67169. }
  67170. if (this._ranges) {
  67171. result._ranges = {};
  67172. for (var rangeName in this._ranges) {
  67173. var range = this._ranges[rangeName];
  67174. if (range) {
  67175. result._ranges[rangeName] = range.clone();
  67176. }
  67177. }
  67178. }
  67179. this._isDirty = true;
  67180. return result;
  67181. };
  67182. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  67183. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  67184. this.bones.forEach(function (bone) {
  67185. bone.animations.forEach(function (animation) {
  67186. animation.enableBlending = true;
  67187. animation.blendingSpeed = blendingSpeed;
  67188. });
  67189. });
  67190. };
  67191. Skeleton.prototype.dispose = function () {
  67192. this._meshesWithPoseMatrix = [];
  67193. // Animations
  67194. this.getScene().stopAnimation(this);
  67195. // Remove from scene
  67196. this.getScene().removeSkeleton(this);
  67197. };
  67198. Skeleton.prototype.serialize = function () {
  67199. var serializationObject = {};
  67200. serializationObject.name = this.name;
  67201. serializationObject.id = this.id;
  67202. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  67203. serializationObject.bones = [];
  67204. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  67205. for (var index = 0; index < this.bones.length; index++) {
  67206. var bone = this.bones[index];
  67207. var parent_2 = bone.getParent();
  67208. var serializedBone = {
  67209. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  67210. name: bone.name,
  67211. matrix: bone.getBaseMatrix().toArray(),
  67212. rest: bone.getRestPose().toArray()
  67213. };
  67214. serializationObject.bones.push(serializedBone);
  67215. if (bone.length) {
  67216. serializedBone.length = bone.length;
  67217. }
  67218. if (bone.animations && bone.animations.length > 0) {
  67219. serializedBone.animation = bone.animations[0].serialize();
  67220. }
  67221. serializationObject.ranges = [];
  67222. for (var name in this._ranges) {
  67223. var source = this._ranges[name];
  67224. if (!source) {
  67225. continue;
  67226. }
  67227. var range = {};
  67228. range.name = name;
  67229. range.from = source.from;
  67230. range.to = source.to;
  67231. serializationObject.ranges.push(range);
  67232. }
  67233. }
  67234. return serializationObject;
  67235. };
  67236. Skeleton.Parse = function (parsedSkeleton, scene) {
  67237. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  67238. if (parsedSkeleton.dimensionsAtRest) {
  67239. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  67240. }
  67241. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  67242. var index;
  67243. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  67244. var parsedBone = parsedSkeleton.bones[index];
  67245. var parentBone = null;
  67246. if (parsedBone.parentBoneIndex > -1) {
  67247. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  67248. }
  67249. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  67250. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  67251. if (parsedBone.length) {
  67252. bone.length = parsedBone.length;
  67253. }
  67254. if (parsedBone.animation) {
  67255. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  67256. }
  67257. }
  67258. // placed after bones, so createAnimationRange can cascade down
  67259. if (parsedSkeleton.ranges) {
  67260. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  67261. var data = parsedSkeleton.ranges[index];
  67262. skeleton.createAnimationRange(data.name, data.from, data.to);
  67263. }
  67264. }
  67265. return skeleton;
  67266. };
  67267. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  67268. if (forceUpdate === void 0) { forceUpdate = false; }
  67269. var renderId = this._scene.getRenderId();
  67270. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  67271. this.bones[0].computeAbsoluteTransforms();
  67272. this._lastAbsoluteTransformsUpdateId = renderId;
  67273. }
  67274. };
  67275. Skeleton.prototype.getPoseMatrix = function () {
  67276. var poseMatrix = null;
  67277. if (this._meshesWithPoseMatrix.length > 0) {
  67278. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  67279. }
  67280. return poseMatrix;
  67281. };
  67282. Skeleton.prototype.sortBones = function () {
  67283. var bones = new Array();
  67284. var visited = new Array(this.bones.length);
  67285. for (var index = 0; index < this.bones.length; index++) {
  67286. this._sortBones(index, bones, visited);
  67287. }
  67288. this.bones = bones;
  67289. };
  67290. Skeleton.prototype._sortBones = function (index, bones, visited) {
  67291. if (visited[index]) {
  67292. return;
  67293. }
  67294. visited[index] = true;
  67295. var bone = this.bones[index];
  67296. if (bone._index === undefined) {
  67297. bone._index = index;
  67298. }
  67299. var parentBone = bone.getParent();
  67300. if (parentBone) {
  67301. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  67302. }
  67303. bones.push(bone);
  67304. };
  67305. return Skeleton;
  67306. }());
  67307. BABYLON.Skeleton = Skeleton;
  67308. })(BABYLON || (BABYLON = {}));
  67309. //# sourceMappingURL=babylon.skeleton.js.map
  67310. var BABYLON;
  67311. (function (BABYLON) {
  67312. var SphericalPolynomial = /** @class */ (function () {
  67313. function SphericalPolynomial() {
  67314. this.x = BABYLON.Vector3.Zero();
  67315. this.y = BABYLON.Vector3.Zero();
  67316. this.z = BABYLON.Vector3.Zero();
  67317. this.xx = BABYLON.Vector3.Zero();
  67318. this.yy = BABYLON.Vector3.Zero();
  67319. this.zz = BABYLON.Vector3.Zero();
  67320. this.xy = BABYLON.Vector3.Zero();
  67321. this.yz = BABYLON.Vector3.Zero();
  67322. this.zx = BABYLON.Vector3.Zero();
  67323. }
  67324. SphericalPolynomial.prototype.addAmbient = function (color) {
  67325. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  67326. this.xx = this.xx.add(colorVector);
  67327. this.yy = this.yy.add(colorVector);
  67328. this.zz = this.zz.add(colorVector);
  67329. };
  67330. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  67331. var result = new SphericalPolynomial();
  67332. result.x = harmonics.L11.scale(1.02333);
  67333. result.y = harmonics.L1_1.scale(1.02333);
  67334. result.z = harmonics.L10.scale(1.02333);
  67335. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  67336. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  67337. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  67338. result.yz = harmonics.L2_1.scale(0.858086);
  67339. result.zx = harmonics.L21.scale(0.858086);
  67340. result.xy = harmonics.L2_2.scale(0.858086);
  67341. result.scale(1.0 / Math.PI);
  67342. return result;
  67343. };
  67344. SphericalPolynomial.prototype.scale = function (scale) {
  67345. this.x = this.x.scale(scale);
  67346. this.y = this.y.scale(scale);
  67347. this.z = this.z.scale(scale);
  67348. this.xx = this.xx.scale(scale);
  67349. this.yy = this.yy.scale(scale);
  67350. this.zz = this.zz.scale(scale);
  67351. this.yz = this.yz.scale(scale);
  67352. this.zx = this.zx.scale(scale);
  67353. this.xy = this.xy.scale(scale);
  67354. };
  67355. return SphericalPolynomial;
  67356. }());
  67357. BABYLON.SphericalPolynomial = SphericalPolynomial;
  67358. var SphericalHarmonics = /** @class */ (function () {
  67359. function SphericalHarmonics() {
  67360. this.L00 = BABYLON.Vector3.Zero();
  67361. this.L1_1 = BABYLON.Vector3.Zero();
  67362. this.L10 = BABYLON.Vector3.Zero();
  67363. this.L11 = BABYLON.Vector3.Zero();
  67364. this.L2_2 = BABYLON.Vector3.Zero();
  67365. this.L2_1 = BABYLON.Vector3.Zero();
  67366. this.L20 = BABYLON.Vector3.Zero();
  67367. this.L21 = BABYLON.Vector3.Zero();
  67368. this.L22 = BABYLON.Vector3.Zero();
  67369. }
  67370. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  67371. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  67372. var c = colorVector.scale(deltaSolidAngle);
  67373. this.L00 = this.L00.add(c.scale(0.282095));
  67374. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  67375. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  67376. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  67377. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  67378. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  67379. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  67380. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  67381. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  67382. };
  67383. SphericalHarmonics.prototype.scale = function (scale) {
  67384. this.L00 = this.L00.scale(scale);
  67385. this.L1_1 = this.L1_1.scale(scale);
  67386. this.L10 = this.L10.scale(scale);
  67387. this.L11 = this.L11.scale(scale);
  67388. this.L2_2 = this.L2_2.scale(scale);
  67389. this.L2_1 = this.L2_1.scale(scale);
  67390. this.L20 = this.L20.scale(scale);
  67391. this.L21 = this.L21.scale(scale);
  67392. this.L22 = this.L22.scale(scale);
  67393. };
  67394. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  67395. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  67396. //
  67397. // E_lm = A_l * L_lm
  67398. //
  67399. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  67400. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  67401. // the scaling factors are given in equation 9.
  67402. // Constant (Band 0)
  67403. this.L00 = this.L00.scale(3.141593);
  67404. // Linear (Band 1)
  67405. this.L1_1 = this.L1_1.scale(2.094395);
  67406. this.L10 = this.L10.scale(2.094395);
  67407. this.L11 = this.L11.scale(2.094395);
  67408. // Quadratic (Band 2)
  67409. this.L2_2 = this.L2_2.scale(0.785398);
  67410. this.L2_1 = this.L2_1.scale(0.785398);
  67411. this.L20 = this.L20.scale(0.785398);
  67412. this.L21 = this.L21.scale(0.785398);
  67413. this.L22 = this.L22.scale(0.785398);
  67414. };
  67415. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  67416. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  67417. // L = (1/pi) * E * rho
  67418. //
  67419. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  67420. this.scale(1.0 / Math.PI);
  67421. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  67422. // (The pixel shader must apply albedo after texture fetches, etc).
  67423. };
  67424. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  67425. var result = new SphericalHarmonics();
  67426. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  67427. result.L1_1 = polynomial.y.scale(0.977204);
  67428. result.L10 = polynomial.z.scale(0.977204);
  67429. result.L11 = polynomial.x.scale(0.977204);
  67430. result.L2_2 = polynomial.xy.scale(1.16538);
  67431. result.L2_1 = polynomial.yz.scale(1.16538);
  67432. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  67433. result.L21 = polynomial.zx.scale(1.16538);
  67434. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  67435. result.scale(Math.PI);
  67436. return result;
  67437. };
  67438. return SphericalHarmonics;
  67439. }());
  67440. BABYLON.SphericalHarmonics = SphericalHarmonics;
  67441. })(BABYLON || (BABYLON = {}));
  67442. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  67443. var BABYLON;
  67444. (function (BABYLON) {
  67445. var FileFaceOrientation = /** @class */ (function () {
  67446. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  67447. this.name = name;
  67448. this.worldAxisForNormal = worldAxisForNormal;
  67449. this.worldAxisForFileX = worldAxisForFileX;
  67450. this.worldAxisForFileY = worldAxisForFileY;
  67451. }
  67452. return FileFaceOrientation;
  67453. }());
  67454. ;
  67455. /**
  67456. * Helper class dealing with the extraction of spherical polynomial dataArray
  67457. * from a cube map.
  67458. */
  67459. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  67460. function CubeMapToSphericalPolynomialTools() {
  67461. }
  67462. /**
  67463. * Converts a texture to the according Spherical Polynomial data.
  67464. * This extracts the first 3 orders only as they are the only one used in the lighting.
  67465. *
  67466. * @param texture The texture to extract the information from.
  67467. * @return The Spherical Polynomial data.
  67468. */
  67469. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  67470. if (!texture.isCube) {
  67471. // Only supports cube Textures currently.
  67472. return null;
  67473. }
  67474. var size = texture.getSize().width;
  67475. var right = texture.readPixels(0);
  67476. var left = texture.readPixels(1);
  67477. var up;
  67478. var down;
  67479. if (texture.isRenderTarget) {
  67480. up = texture.readPixels(3);
  67481. down = texture.readPixels(2);
  67482. }
  67483. else {
  67484. up = texture.readPixels(2);
  67485. down = texture.readPixels(3);
  67486. }
  67487. var front = texture.readPixels(4);
  67488. var back = texture.readPixels(5);
  67489. var gammaSpace = texture.gammaSpace;
  67490. // Always read as RGBA.
  67491. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  67492. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  67493. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  67494. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  67495. }
  67496. var cubeInfo = {
  67497. size: size,
  67498. right: right,
  67499. left: left,
  67500. up: up,
  67501. down: down,
  67502. front: front,
  67503. back: back,
  67504. format: format,
  67505. type: type,
  67506. gammaSpace: gammaSpace,
  67507. };
  67508. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  67509. };
  67510. /**
  67511. * Converts a cubemap to the according Spherical Polynomial data.
  67512. * This extracts the first 3 orders only as they are the only one used in the lighting.
  67513. *
  67514. * @param cubeInfo The Cube map to extract the information from.
  67515. * @return The Spherical Polynomial data.
  67516. */
  67517. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  67518. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  67519. var totalSolidAngle = 0.0;
  67520. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  67521. var du = 2.0 / cubeInfo.size;
  67522. var dv = du;
  67523. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  67524. var minUV = du * 0.5 - 1.0;
  67525. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  67526. var fileFace = this.FileFaces[faceIndex];
  67527. var dataArray = cubeInfo[fileFace.name];
  67528. var v = minUV;
  67529. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  67530. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  67531. // Because SP is still linear, so summation is fine in that basis.
  67532. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  67533. for (var y = 0; y < cubeInfo.size; y++) {
  67534. var u = minUV;
  67535. for (var x = 0; x < cubeInfo.size; x++) {
  67536. // World direction (not normalised)
  67537. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  67538. worldDirection.normalize();
  67539. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  67540. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  67541. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  67542. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  67543. // Handle Integer types.
  67544. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  67545. r /= 255;
  67546. g /= 255;
  67547. b /= 255;
  67548. }
  67549. // Handle Gamma space textures.
  67550. if (cubeInfo.gammaSpace) {
  67551. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  67552. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  67553. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  67554. }
  67555. var color = new BABYLON.Color3(r, g, b);
  67556. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  67557. totalSolidAngle += deltaSolidAngle;
  67558. u += du;
  67559. }
  67560. v += dv;
  67561. }
  67562. }
  67563. // Solid angle for entire sphere is 4*pi
  67564. var sphereSolidAngle = 4.0 * Math.PI;
  67565. // Adjust the solid angle to allow for how many faces we processed.
  67566. var facesProcessed = 6.0;
  67567. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  67568. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  67569. // This is needed because the numerical integration over the cube uses a
  67570. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  67571. // and also to compensate for accumulative error due to float precision in the summation.
  67572. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  67573. sphericalHarmonics.scale(correctionFactor);
  67574. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  67575. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  67576. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  67577. };
  67578. CubeMapToSphericalPolynomialTools.FileFaces = [
  67579. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  67580. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  67581. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  67582. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  67583. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  67584. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  67585. ];
  67586. return CubeMapToSphericalPolynomialTools;
  67587. }());
  67588. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  67589. })(BABYLON || (BABYLON = {}));
  67590. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  67591. var BABYLON;
  67592. (function (BABYLON) {
  67593. /**
  67594. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  67595. */
  67596. var PanoramaToCubeMapTools = /** @class */ (function () {
  67597. function PanoramaToCubeMapTools() {
  67598. }
  67599. /**
  67600. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  67601. *
  67602. * @param float32Array The source data.
  67603. * @param inputWidth The width of the input panorama.
  67604. * @param inputhHeight The height of the input panorama.
  67605. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  67606. * @return The cubemap data
  67607. */
  67608. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  67609. if (!float32Array) {
  67610. throw "ConvertPanoramaToCubemap: input cannot be null";
  67611. }
  67612. if (float32Array.length != inputWidth * inputHeight * 3) {
  67613. throw "ConvertPanoramaToCubemap: input size is wrong";
  67614. }
  67615. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  67616. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  67617. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  67618. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  67619. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  67620. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  67621. return {
  67622. front: textureFront,
  67623. back: textureBack,
  67624. left: textureLeft,
  67625. right: textureRight,
  67626. up: textureUp,
  67627. down: textureDown,
  67628. size: size,
  67629. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  67630. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  67631. gammaSpace: false,
  67632. };
  67633. };
  67634. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  67635. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  67636. var textureArray = new Float32Array(buffer);
  67637. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  67638. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  67639. var dy = 1 / texSize;
  67640. var fy = 0;
  67641. for (var y = 0; y < texSize; y++) {
  67642. var xv1 = faceData[0];
  67643. var xv2 = faceData[2];
  67644. for (var x = 0; x < texSize; x++) {
  67645. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  67646. v.normalize();
  67647. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  67648. // 3 channels per pixels
  67649. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  67650. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  67651. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  67652. xv1 = xv1.add(rotDX1);
  67653. xv2 = xv2.add(rotDX2);
  67654. }
  67655. fy += dy;
  67656. }
  67657. return textureArray;
  67658. };
  67659. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  67660. var theta = Math.atan2(vDir.z, vDir.x);
  67661. var phi = Math.acos(vDir.y);
  67662. while (theta < -Math.PI)
  67663. theta += 2 * Math.PI;
  67664. while (theta > Math.PI)
  67665. theta -= 2 * Math.PI;
  67666. var dx = theta / Math.PI;
  67667. var dy = phi / Math.PI;
  67668. // recenter.
  67669. dx = dx * 0.5 + 0.5;
  67670. var px = Math.round(dx * inputWidth);
  67671. if (px < 0)
  67672. px = 0;
  67673. else if (px >= inputWidth)
  67674. px = inputWidth - 1;
  67675. var py = Math.round(dy * inputHeight);
  67676. if (py < 0)
  67677. py = 0;
  67678. else if (py >= inputHeight)
  67679. py = inputHeight - 1;
  67680. var inputY = (inputHeight - py - 1);
  67681. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  67682. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  67683. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  67684. return {
  67685. r: r,
  67686. g: g,
  67687. b: b
  67688. };
  67689. };
  67690. PanoramaToCubeMapTools.FACE_FRONT = [
  67691. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  67692. new BABYLON.Vector3(1.0, -1.0, -1.0),
  67693. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  67694. new BABYLON.Vector3(1.0, 1.0, -1.0)
  67695. ];
  67696. PanoramaToCubeMapTools.FACE_BACK = [
  67697. new BABYLON.Vector3(1.0, -1.0, 1.0),
  67698. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  67699. new BABYLON.Vector3(1.0, 1.0, 1.0),
  67700. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  67701. ];
  67702. PanoramaToCubeMapTools.FACE_RIGHT = [
  67703. new BABYLON.Vector3(1.0, -1.0, -1.0),
  67704. new BABYLON.Vector3(1.0, -1.0, 1.0),
  67705. new BABYLON.Vector3(1.0, 1.0, -1.0),
  67706. new BABYLON.Vector3(1.0, 1.0, 1.0)
  67707. ];
  67708. PanoramaToCubeMapTools.FACE_LEFT = [
  67709. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  67710. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  67711. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  67712. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  67713. ];
  67714. PanoramaToCubeMapTools.FACE_DOWN = [
  67715. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  67716. new BABYLON.Vector3(1.0, 1.0, -1.0),
  67717. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  67718. new BABYLON.Vector3(1.0, 1.0, 1.0)
  67719. ];
  67720. PanoramaToCubeMapTools.FACE_UP = [
  67721. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  67722. new BABYLON.Vector3(1.0, -1.0, 1.0),
  67723. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  67724. new BABYLON.Vector3(1.0, -1.0, -1.0)
  67725. ];
  67726. return PanoramaToCubeMapTools;
  67727. }());
  67728. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  67729. })(BABYLON || (BABYLON = {}));
  67730. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  67731. var BABYLON;
  67732. (function (BABYLON) {
  67733. ;
  67734. /**
  67735. * This groups tools to convert HDR texture to native colors array.
  67736. */
  67737. var HDRTools = /** @class */ (function () {
  67738. function HDRTools() {
  67739. }
  67740. HDRTools.Ldexp = function (mantissa, exponent) {
  67741. if (exponent > 1023) {
  67742. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  67743. }
  67744. if (exponent < -1074) {
  67745. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  67746. }
  67747. return mantissa * Math.pow(2, exponent);
  67748. };
  67749. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  67750. if (exponent > 0) {
  67751. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  67752. float32array[index + 0] = red * exponent;
  67753. float32array[index + 1] = green * exponent;
  67754. float32array[index + 2] = blue * exponent;
  67755. }
  67756. else {
  67757. float32array[index + 0] = 0;
  67758. float32array[index + 1] = 0;
  67759. float32array[index + 2] = 0;
  67760. }
  67761. };
  67762. HDRTools.readStringLine = function (uint8array, startIndex) {
  67763. var line = "";
  67764. var character = "";
  67765. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  67766. character = String.fromCharCode(uint8array[i]);
  67767. if (character == "\n") {
  67768. break;
  67769. }
  67770. line += character;
  67771. }
  67772. return line;
  67773. };
  67774. /**
  67775. * Reads header information from an RGBE texture stored in a native array.
  67776. * More information on this format are available here:
  67777. * https://en.wikipedia.org/wiki/RGBE_image_format
  67778. *
  67779. * @param uint8array The binary file stored in native array.
  67780. * @return The header information.
  67781. */
  67782. HDRTools.RGBE_ReadHeader = function (uint8array) {
  67783. var height = 0;
  67784. var width = 0;
  67785. var line = this.readStringLine(uint8array, 0);
  67786. if (line[0] != '#' || line[1] != '?') {
  67787. throw "Bad HDR Format.";
  67788. }
  67789. var endOfHeader = false;
  67790. var findFormat = false;
  67791. var lineIndex = 0;
  67792. do {
  67793. lineIndex += (line.length + 1);
  67794. line = this.readStringLine(uint8array, lineIndex);
  67795. if (line == "FORMAT=32-bit_rle_rgbe") {
  67796. findFormat = true;
  67797. }
  67798. else if (line.length == 0) {
  67799. endOfHeader = true;
  67800. }
  67801. } while (!endOfHeader);
  67802. if (!findFormat) {
  67803. throw "HDR Bad header format, unsupported FORMAT";
  67804. }
  67805. lineIndex += (line.length + 1);
  67806. line = this.readStringLine(uint8array, lineIndex);
  67807. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  67808. var match = sizeRegexp.exec(line);
  67809. // TODO. Support +Y and -X if needed.
  67810. if (!match || match.length < 3) {
  67811. throw "HDR Bad header format, no size";
  67812. }
  67813. width = parseInt(match[2]);
  67814. height = parseInt(match[1]);
  67815. if (width < 8 || width > 0x7fff) {
  67816. throw "HDR Bad header format, unsupported size";
  67817. }
  67818. lineIndex += (line.length + 1);
  67819. return {
  67820. height: height,
  67821. width: width,
  67822. dataPosition: lineIndex
  67823. };
  67824. };
  67825. /**
  67826. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  67827. * This RGBE texture needs to store the information as a panorama.
  67828. *
  67829. * More information on this format are available here:
  67830. * https://en.wikipedia.org/wiki/RGBE_image_format
  67831. *
  67832. * @param buffer The binary file stored in an array buffer.
  67833. * @param size The expected size of the extracted cubemap.
  67834. * @return The Cube Map information.
  67835. */
  67836. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  67837. var uint8array = new Uint8Array(buffer);
  67838. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  67839. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  67840. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  67841. return cubeMapData;
  67842. };
  67843. /**
  67844. * Returns the pixels data extracted from an RGBE texture.
  67845. * This pixels will be stored left to right up to down in the R G B order in one array.
  67846. *
  67847. * More information on this format are available here:
  67848. * https://en.wikipedia.org/wiki/RGBE_image_format
  67849. *
  67850. * @param uint8array The binary file stored in an array buffer.
  67851. * @param hdrInfo The header information of the file.
  67852. * @return The pixels data in RGB right to left up to down order.
  67853. */
  67854. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  67855. // Keep for multi format supports.
  67856. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  67857. };
  67858. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  67859. var num_scanlines = hdrInfo.height;
  67860. var scanline_width = hdrInfo.width;
  67861. var a, b, c, d, count;
  67862. var dataIndex = hdrInfo.dataPosition;
  67863. var index = 0, endIndex = 0, i = 0;
  67864. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  67865. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  67866. // 3 channels of 4 bytes per pixel in float.
  67867. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  67868. var resultArray = new Float32Array(resultBuffer);
  67869. // read in each successive scanline
  67870. while (num_scanlines > 0) {
  67871. a = uint8array[dataIndex++];
  67872. b = uint8array[dataIndex++];
  67873. c = uint8array[dataIndex++];
  67874. d = uint8array[dataIndex++];
  67875. if (a != 2 || b != 2 || (c & 0x80)) {
  67876. // this file is not run length encoded
  67877. throw "HDR Bad header format, not RLE";
  67878. }
  67879. if (((c << 8) | d) != scanline_width) {
  67880. throw "HDR Bad header format, wrong scan line width";
  67881. }
  67882. index = 0;
  67883. // read each of the four channels for the scanline into the buffer
  67884. for (i = 0; i < 4; i++) {
  67885. endIndex = (i + 1) * scanline_width;
  67886. while (index < endIndex) {
  67887. a = uint8array[dataIndex++];
  67888. b = uint8array[dataIndex++];
  67889. if (a > 128) {
  67890. // a run of the same value
  67891. count = a - 128;
  67892. if ((count == 0) || (count > endIndex - index)) {
  67893. throw "HDR Bad Format, bad scanline data (run)";
  67894. }
  67895. while (count-- > 0) {
  67896. scanLineArray[index++] = b;
  67897. }
  67898. }
  67899. else {
  67900. // a non-run
  67901. count = a;
  67902. if ((count == 0) || (count > endIndex - index)) {
  67903. throw "HDR Bad Format, bad scanline data (non-run)";
  67904. }
  67905. scanLineArray[index++] = b;
  67906. if (--count > 0) {
  67907. for (var j = 0; j < count; j++) {
  67908. scanLineArray[index++] = uint8array[dataIndex++];
  67909. }
  67910. }
  67911. }
  67912. }
  67913. }
  67914. // now convert data from buffer into floats
  67915. for (i = 0; i < scanline_width; i++) {
  67916. a = scanLineArray[i];
  67917. b = scanLineArray[i + scanline_width];
  67918. c = scanLineArray[i + 2 * scanline_width];
  67919. d = scanLineArray[i + 3 * scanline_width];
  67920. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  67921. }
  67922. num_scanlines--;
  67923. }
  67924. return resultArray;
  67925. };
  67926. return HDRTools;
  67927. }());
  67928. BABYLON.HDRTools = HDRTools;
  67929. })(BABYLON || (BABYLON = {}));
  67930. //# sourceMappingURL=babylon.hdr.js.map
  67931. var BABYLON;
  67932. (function (BABYLON) {
  67933. /**
  67934. * This represents a texture coming from an HDR input.
  67935. *
  67936. * The only supported format is currently panorama picture stored in RGBE format.
  67937. * Example of such files can be found on HDRLib: http://hdrlib.com/
  67938. */
  67939. var HDRCubeTexture = /** @class */ (function (_super) {
  67940. __extends(HDRCubeTexture, _super);
  67941. /**
  67942. * Instantiates an HDRTexture from the following parameters.
  67943. *
  67944. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  67945. * @param scene The scene the texture will be used in
  67946. * @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.
  67947. * @param noMipmap Forces to not generate the mipmap if true
  67948. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  67949. * @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)
  67950. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  67951. */
  67952. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  67953. if (noMipmap === void 0) { noMipmap = false; }
  67954. if (generateHarmonics === void 0) { generateHarmonics = true; }
  67955. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  67956. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  67957. if (onLoad === void 0) { onLoad = null; }
  67958. if (onError === void 0) { onError = null; }
  67959. var _this = _super.call(this, scene) || this;
  67960. _this._useInGammaSpace = false;
  67961. _this._generateHarmonics = true;
  67962. _this._isBABYLONPreprocessed = false;
  67963. _this._onLoad = null;
  67964. _this._onError = null;
  67965. /**
  67966. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  67967. */
  67968. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  67969. /**
  67970. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  67971. * This is usefull at run time to apply the good shader.
  67972. */
  67973. _this.isPMREM = false;
  67974. _this._isBlocking = true;
  67975. if (!url) {
  67976. return _this;
  67977. }
  67978. _this.name = url;
  67979. _this.url = url;
  67980. _this.hasAlpha = false;
  67981. _this.isCube = true;
  67982. _this._textureMatrix = BABYLON.Matrix.Identity();
  67983. _this._onLoad = onLoad;
  67984. _this._onError = onError;
  67985. _this.gammaSpace = false;
  67986. var caps = scene.getEngine().getCaps();
  67987. if (size) {
  67988. _this._isBABYLONPreprocessed = false;
  67989. _this._noMipmap = noMipmap;
  67990. _this._size = size;
  67991. _this._useInGammaSpace = useInGammaSpace;
  67992. _this._usePMREMGenerator = usePMREMGenerator &&
  67993. caps.textureLOD &&
  67994. caps.textureFloat &&
  67995. !_this._useInGammaSpace;
  67996. }
  67997. else {
  67998. _this._isBABYLONPreprocessed = true;
  67999. _this._noMipmap = false;
  68000. _this._useInGammaSpace = false;
  68001. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  68002. !_this._useInGammaSpace;
  68003. }
  68004. _this.isPMREM = _this._usePMREMGenerator;
  68005. _this._texture = _this._getFromCache(url, _this._noMipmap);
  68006. if (!_this._texture) {
  68007. if (!scene.useDelayedTextureLoading) {
  68008. _this.loadTexture();
  68009. }
  68010. else {
  68011. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  68012. }
  68013. }
  68014. return _this;
  68015. }
  68016. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  68017. /**
  68018. * Gets wether or not the texture is blocking during loading.
  68019. */
  68020. get: function () {
  68021. return this._isBlocking;
  68022. },
  68023. /**
  68024. * Sets wether or not the texture is blocking during loading.
  68025. */
  68026. set: function (value) {
  68027. this._isBlocking = value;
  68028. },
  68029. enumerable: true,
  68030. configurable: true
  68031. });
  68032. /**
  68033. * Occurs when the file is a preprocessed .babylon.hdr file.
  68034. */
  68035. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  68036. var _this = this;
  68037. var mipLevels = 0;
  68038. var floatArrayView = null;
  68039. var scene = this.getScene();
  68040. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  68041. var mips = new Array();
  68042. if (!floatArrayView) {
  68043. return mips;
  68044. }
  68045. var startIndex = 30;
  68046. for (var level = 0; level < mipLevels; level++) {
  68047. mips.push([]);
  68048. // Fill each pixel of the mip level.
  68049. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  68050. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  68051. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  68052. mips[level].push(faceData);
  68053. startIndex += faceSize;
  68054. }
  68055. }
  68056. return mips;
  68057. } : null;
  68058. var callback = function (buffer) {
  68059. var scene = _this.getScene();
  68060. if (!scene) {
  68061. return null;
  68062. }
  68063. // Create Native Array Views
  68064. var intArrayView = new Int32Array(buffer);
  68065. floatArrayView = new Float32Array(buffer);
  68066. // Fill header.
  68067. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  68068. _this._size = intArrayView[1]; // CubeMap max mip face size.
  68069. // Update Texture Information.
  68070. if (!_this._texture) {
  68071. return null;
  68072. }
  68073. _this._texture.updateSize(_this._size, _this._size);
  68074. // Fill polynomial information.
  68075. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  68076. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  68077. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  68078. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  68079. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  68080. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  68081. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  68082. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  68083. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  68084. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  68085. _this.sphericalPolynomial = sphericalPolynomial;
  68086. // Fill pixel data.
  68087. mipLevels = intArrayView[29]; // Number of mip levels.
  68088. var startIndex = 30;
  68089. var data = [];
  68090. var faceSize = Math.pow(_this._size, 2) * 3;
  68091. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  68092. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  68093. startIndex += faceSize;
  68094. }
  68095. var results = [];
  68096. var byteArray = null;
  68097. // Push each faces.
  68098. for (var k = 0; k < 6; k++) {
  68099. var dataFace = null;
  68100. // To be deprecated.
  68101. if (version === 1) {
  68102. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  68103. dataFace = data[j];
  68104. }
  68105. // If special cases.
  68106. if (!mipmapGenerator && dataFace) {
  68107. if (!scene.getEngine().getCaps().textureFloat) {
  68108. // 3 channels of 1 bytes per pixel in bytes.
  68109. var byteBuffer = new ArrayBuffer(faceSize);
  68110. byteArray = new Uint8Array(byteBuffer);
  68111. }
  68112. for (var i = 0; i < _this._size * _this._size; i++) {
  68113. // Put in gamma space if requested.
  68114. if (_this._useInGammaSpace) {
  68115. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  68116. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  68117. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  68118. }
  68119. // Convert to int texture for fallback.
  68120. if (byteArray) {
  68121. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  68122. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  68123. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  68124. // May use luminance instead if the result is not accurate.
  68125. var max = Math.max(Math.max(r, g), b);
  68126. if (max > 255) {
  68127. var scale = 255 / max;
  68128. r *= scale;
  68129. g *= scale;
  68130. b *= scale;
  68131. }
  68132. byteArray[(i * 3) + 0] = r;
  68133. byteArray[(i * 3) + 1] = g;
  68134. byteArray[(i * 3) + 2] = b;
  68135. }
  68136. }
  68137. }
  68138. // Fill the array accordingly.
  68139. if (byteArray) {
  68140. results.push(byteArray);
  68141. }
  68142. else {
  68143. results.push(dataFace);
  68144. }
  68145. }
  68146. return results;
  68147. };
  68148. if (scene) {
  68149. 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);
  68150. }
  68151. };
  68152. /**
  68153. * Occurs when the file is raw .hdr file.
  68154. */
  68155. HDRCubeTexture.prototype.loadHDRTexture = function () {
  68156. var _this = this;
  68157. var callback = function (buffer) {
  68158. var scene = _this.getScene();
  68159. if (!scene) {
  68160. return null;
  68161. }
  68162. // Extract the raw linear data.
  68163. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  68164. // Generate harmonics if needed.
  68165. if (_this._generateHarmonics) {
  68166. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  68167. _this.sphericalPolynomial = sphericalPolynomial;
  68168. }
  68169. var results = [];
  68170. var byteArray = null;
  68171. // Push each faces.
  68172. for (var j = 0; j < 6; j++) {
  68173. // Create uintarray fallback.
  68174. if (!scene.getEngine().getCaps().textureFloat) {
  68175. // 3 channels of 1 bytes per pixel in bytes.
  68176. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  68177. byteArray = new Uint8Array(byteBuffer);
  68178. }
  68179. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  68180. // If special cases.
  68181. if (_this._useInGammaSpace || byteArray) {
  68182. for (var i = 0; i < _this._size * _this._size; i++) {
  68183. // Put in gamma space if requested.
  68184. if (_this._useInGammaSpace) {
  68185. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  68186. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  68187. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  68188. }
  68189. // Convert to int texture for fallback.
  68190. if (byteArray) {
  68191. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  68192. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  68193. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  68194. // May use luminance instead if the result is not accurate.
  68195. var max = Math.max(Math.max(r, g), b);
  68196. if (max > 255) {
  68197. var scale = 255 / max;
  68198. r *= scale;
  68199. g *= scale;
  68200. b *= scale;
  68201. }
  68202. byteArray[(i * 3) + 0] = r;
  68203. byteArray[(i * 3) + 1] = g;
  68204. byteArray[(i * 3) + 2] = b;
  68205. }
  68206. }
  68207. }
  68208. if (byteArray) {
  68209. results.push(byteArray);
  68210. }
  68211. else {
  68212. results.push(dataFace);
  68213. }
  68214. }
  68215. return results;
  68216. };
  68217. var mipmapGenerator = null;
  68218. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  68219. // if (!this._noMipmap &&
  68220. // this._usePMREMGenerator) {
  68221. // mipmapGenerator = (data: ArrayBufferView[]) => {
  68222. // // Custom setup of the generator matching with the PBR shader values.
  68223. // var generator = new BABYLON.PMREMGenerator(data,
  68224. // this._size,
  68225. // this._size,
  68226. // 0,
  68227. // 3,
  68228. // this.getScene().getEngine().getCaps().textureFloat,
  68229. // 2048,
  68230. // 0.25,
  68231. // false,
  68232. // true);
  68233. // return generator.filterCubeMap();
  68234. // };
  68235. // }
  68236. var scene = this.getScene();
  68237. if (scene) {
  68238. 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);
  68239. }
  68240. };
  68241. /**
  68242. * Starts the loading process of the texture.
  68243. */
  68244. HDRCubeTexture.prototype.loadTexture = function () {
  68245. if (this._isBABYLONPreprocessed) {
  68246. this.loadBabylonTexture();
  68247. }
  68248. else {
  68249. this.loadHDRTexture();
  68250. }
  68251. };
  68252. HDRCubeTexture.prototype.clone = function () {
  68253. var scene = this.getScene();
  68254. if (!scene) {
  68255. return this;
  68256. }
  68257. var size = (this._isBABYLONPreprocessed ? null : this._size);
  68258. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  68259. // Base texture
  68260. newTexture.level = this.level;
  68261. newTexture.wrapU = this.wrapU;
  68262. newTexture.wrapV = this.wrapV;
  68263. newTexture.coordinatesIndex = this.coordinatesIndex;
  68264. newTexture.coordinatesMode = this.coordinatesMode;
  68265. return newTexture;
  68266. };
  68267. // Methods
  68268. HDRCubeTexture.prototype.delayLoad = function () {
  68269. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  68270. return;
  68271. }
  68272. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  68273. this._texture = this._getFromCache(this.url, this._noMipmap);
  68274. if (!this._texture) {
  68275. this.loadTexture();
  68276. }
  68277. };
  68278. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  68279. return this._textureMatrix;
  68280. };
  68281. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  68282. this._textureMatrix = value;
  68283. };
  68284. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  68285. var texture = null;
  68286. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  68287. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  68288. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  68289. texture.name = parsedTexture.name;
  68290. texture.hasAlpha = parsedTexture.hasAlpha;
  68291. texture.level = parsedTexture.level;
  68292. texture.coordinatesMode = parsedTexture.coordinatesMode;
  68293. texture.isBlocking = parsedTexture.isBlocking;
  68294. }
  68295. return texture;
  68296. };
  68297. HDRCubeTexture.prototype.serialize = function () {
  68298. if (!this.name) {
  68299. return null;
  68300. }
  68301. var serializationObject = {};
  68302. serializationObject.name = this.name;
  68303. serializationObject.hasAlpha = this.hasAlpha;
  68304. serializationObject.isCube = true;
  68305. serializationObject.level = this.level;
  68306. serializationObject.size = this._size;
  68307. serializationObject.coordinatesMode = this.coordinatesMode;
  68308. serializationObject.useInGammaSpace = this._useInGammaSpace;
  68309. serializationObject.generateHarmonics = this._generateHarmonics;
  68310. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  68311. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  68312. serializationObject.customType = "BABYLON.HDRCubeTexture";
  68313. serializationObject.noMipmap = this._noMipmap;
  68314. serializationObject.isBlocking = this._isBlocking;
  68315. return serializationObject;
  68316. };
  68317. /**
  68318. * Saves as a file the data contained in the texture in a binary format.
  68319. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  68320. * as the spherical used in the lighting.
  68321. * @param url The HDR file url.
  68322. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  68323. * @param onError Method called if any error happens during download.
  68324. * @return The packed binary data.
  68325. */
  68326. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  68327. if (onError === void 0) { onError = null; }
  68328. var callback = function (buffer) {
  68329. var data = new Blob([buffer], { type: 'application/octet-stream' });
  68330. // Returns a URL you can use as a href.
  68331. var objUrl = window.URL.createObjectURL(data);
  68332. // Simulates a link to it and click to dowload.
  68333. var a = document.createElement("a");
  68334. document.body.appendChild(a);
  68335. a.style.display = "none";
  68336. a.href = objUrl;
  68337. a.download = "envmap.babylon.hdr";
  68338. a.click();
  68339. };
  68340. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  68341. };
  68342. /**
  68343. * Serializes the data contained in the texture in a binary format.
  68344. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  68345. * as the spherical used in the lighting.
  68346. * @param url The HDR file url.
  68347. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  68348. * @param onError Method called if any error happens during download.
  68349. * @return The packed binary data.
  68350. */
  68351. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  68352. if (onError === void 0) { onError = null; }
  68353. // Needs the url tho create the texture.
  68354. if (!url) {
  68355. return;
  68356. }
  68357. // Check Power of two size.
  68358. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  68359. return;
  68360. }
  68361. // Coming Back in 3.x.
  68362. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  68363. };
  68364. HDRCubeTexture._facesMapping = [
  68365. "right",
  68366. "left",
  68367. "up",
  68368. "down",
  68369. "front",
  68370. "back"
  68371. ];
  68372. return HDRCubeTexture;
  68373. }(BABYLON.BaseTexture));
  68374. BABYLON.HDRCubeTexture = HDRCubeTexture;
  68375. })(BABYLON || (BABYLON = {}));
  68376. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  68377. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  68378. // Huge respect for a such great lib.
  68379. // Earcut license:
  68380. // Copyright (c) 2016, Mapbox
  68381. //
  68382. // Permission to use, copy, modify, and/or distribute this software for any purpose
  68383. // with or without fee is hereby granted, provided that the above copyright notice
  68384. // and this permission notice appear in all copies.
  68385. //
  68386. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  68387. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  68388. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  68389. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  68390. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  68391. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  68392. // THIS SOFTWARE.
  68393. var Earcut;
  68394. (function (Earcut) {
  68395. /**
  68396. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  68397. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  68398. * @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).
  68399. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  68400. */
  68401. function earcut(data, holeIndices, dim) {
  68402. dim = dim || 2;
  68403. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  68404. if (!outerNode)
  68405. return triangles;
  68406. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  68407. if (hasHoles)
  68408. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  68409. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  68410. if (data.length > 80 * dim) {
  68411. minX = maxX = data[0];
  68412. minY = maxY = data[1];
  68413. for (var i = dim; i < outerLen; i += dim) {
  68414. x = data[i];
  68415. y = data[i + 1];
  68416. if (x < minX)
  68417. minX = x;
  68418. if (y < minY)
  68419. minY = y;
  68420. if (x > maxX)
  68421. maxX = x;
  68422. if (y > maxY)
  68423. maxY = y;
  68424. }
  68425. // minX, minY and size are later used to transform coords into integers for z-order calculation
  68426. size = Math.max(maxX - minX, maxY - minY);
  68427. }
  68428. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  68429. return triangles;
  68430. }
  68431. Earcut.earcut = earcut;
  68432. var Node = /** @class */ (function () {
  68433. function Node(i, x, y) {
  68434. this.i = i;
  68435. this.x = x;
  68436. this.y = y;
  68437. this.prev = null;
  68438. this.next = null;
  68439. this.z = null;
  68440. this.prevZ = null;
  68441. this.nextZ = null;
  68442. this.steiner = false;
  68443. }
  68444. return Node;
  68445. }());
  68446. // create a circular doubly linked list from polygon points in the specified winding order
  68447. function linkedList(data, start, end, dim, clockwise) {
  68448. var i, last = null;
  68449. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  68450. for (i = start; i < end; i += dim)
  68451. last = insertNode(i, data[i], data[i + 1], last);
  68452. }
  68453. else {
  68454. for (i = end - dim; i >= start; i -= dim)
  68455. last = insertNode(i, data[i], data[i + 1], last);
  68456. }
  68457. if (last && equals(last, last.next)) {
  68458. removeNode(last);
  68459. last = last.next;
  68460. }
  68461. return last;
  68462. }
  68463. // eliminate colinear or duplicate points
  68464. function filterPoints(start, end) {
  68465. if (!start)
  68466. return start;
  68467. if (!end)
  68468. end = start;
  68469. var p = start, again;
  68470. do {
  68471. again = false;
  68472. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  68473. removeNode(p);
  68474. p = end = p.prev;
  68475. if (p === p.next)
  68476. return undefined;
  68477. again = true;
  68478. }
  68479. else {
  68480. p = p.next;
  68481. }
  68482. } while (again || p !== end);
  68483. return end;
  68484. }
  68485. // main ear slicing loop which triangulates a polygon (given as a linked list)
  68486. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  68487. if (!ear)
  68488. return;
  68489. // interlink polygon nodes in z-order
  68490. if (!pass && size)
  68491. indexCurve(ear, minX, minY, size);
  68492. var stop = ear, prev, next;
  68493. // iterate through ears, slicing them one by one
  68494. while (ear.prev !== ear.next) {
  68495. prev = ear.prev;
  68496. next = ear.next;
  68497. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  68498. // cut off the triangle
  68499. triangles.push(prev.i / dim);
  68500. triangles.push(ear.i / dim);
  68501. triangles.push(next.i / dim);
  68502. removeNode(ear);
  68503. // skipping the next vertice leads to less sliver triangles
  68504. ear = next.next;
  68505. stop = next.next;
  68506. continue;
  68507. }
  68508. ear = next;
  68509. // if we looped through the whole remaining polygon and can't find any more ears
  68510. if (ear === stop) {
  68511. // try filtering points and slicing again
  68512. if (!pass) {
  68513. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  68514. // if this didn't work, try curing all small self-intersections locally
  68515. }
  68516. else if (pass === 1) {
  68517. ear = cureLocalIntersections(ear, triangles, dim);
  68518. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  68519. // as a last resort, try splitting the remaining polygon into two
  68520. }
  68521. else if (pass === 2) {
  68522. splitEarcut(ear, triangles, dim, minX, minY, size);
  68523. }
  68524. break;
  68525. }
  68526. }
  68527. }
  68528. // check whether a polygon node forms a valid ear with adjacent nodes
  68529. function isEar(ear) {
  68530. var a = ear.prev, b = ear, c = ear.next;
  68531. if (area(a, b, c) >= 0)
  68532. return false; // reflex, can't be an ear
  68533. // now make sure we don't have other points inside the potential ear
  68534. var p = ear.next.next;
  68535. while (p !== ear.prev) {
  68536. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  68537. area(p.prev, p, p.next) >= 0)
  68538. return false;
  68539. p = p.next;
  68540. }
  68541. return true;
  68542. }
  68543. function isEarHashed(ear, minX, minY, size) {
  68544. var a = ear.prev, b = ear, c = ear.next;
  68545. if (area(a, b, c) >= 0)
  68546. return false; // reflex, can't be an ear
  68547. // triangle bbox; min & max are calculated like this for speed
  68548. 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);
  68549. // z-order range for the current triangle bbox;
  68550. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  68551. // first look for points inside the triangle in increasing z-order
  68552. var p = ear.nextZ;
  68553. while (p && p.z <= maxZ) {
  68554. if (p !== ear.prev &&
  68555. p !== ear.next &&
  68556. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  68557. area(p.prev, p, p.next) >= 0)
  68558. return false;
  68559. p = p.nextZ;
  68560. }
  68561. // then look for points in decreasing z-order
  68562. p = ear.prevZ;
  68563. while (p && p.z >= minZ) {
  68564. if (p !== ear.prev &&
  68565. p !== ear.next &&
  68566. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  68567. area(p.prev, p, p.next) >= 0)
  68568. return false;
  68569. p = p.prevZ;
  68570. }
  68571. return true;
  68572. }
  68573. // go through all polygon nodes and cure small local self-intersections
  68574. function cureLocalIntersections(start, triangles, dim) {
  68575. var p = start;
  68576. do {
  68577. var a = p.prev, b = p.next.next;
  68578. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  68579. triangles.push(a.i / dim);
  68580. triangles.push(p.i / dim);
  68581. triangles.push(b.i / dim);
  68582. // remove two nodes involved
  68583. removeNode(p);
  68584. removeNode(p.next);
  68585. p = start = b;
  68586. }
  68587. p = p.next;
  68588. } while (p !== start);
  68589. return p;
  68590. }
  68591. // try splitting polygon into two and triangulate them independently
  68592. function splitEarcut(start, triangles, dim, minX, minY, size) {
  68593. // look for a valid diagonal that divides the polygon into two
  68594. var a = start;
  68595. do {
  68596. var b = a.next.next;
  68597. while (b !== a.prev) {
  68598. if (a.i !== b.i && isValidDiagonal(a, b)) {
  68599. // split the polygon in two by the diagonal
  68600. var c = splitPolygon(a, b);
  68601. // filter colinear points around the cuts
  68602. a = filterPoints(a, a.next);
  68603. c = filterPoints(c, c.next);
  68604. // run earcut on each half
  68605. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  68606. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  68607. return;
  68608. }
  68609. b = b.next;
  68610. }
  68611. a = a.next;
  68612. } while (a !== start);
  68613. }
  68614. // link every hole into the outer loop, producing a single-ring polygon without holes
  68615. function eliminateHoles(data, holeIndices, outerNode, dim) {
  68616. var queue = [], i, len, start, end, list;
  68617. for (i = 0, len = holeIndices.length; i < len; i++) {
  68618. start = holeIndices[i] * dim;
  68619. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  68620. list = linkedList(data, start, end, dim, false);
  68621. if (list === list.next)
  68622. list.steiner = true;
  68623. queue.push(getLeftmost(list));
  68624. }
  68625. queue.sort(compareX);
  68626. // process holes from left to right
  68627. for (i = 0; i < queue.length; i++) {
  68628. eliminateHole(queue[i], outerNode);
  68629. outerNode = filterPoints(outerNode, outerNode.next);
  68630. }
  68631. return outerNode;
  68632. }
  68633. function compareX(a, b) {
  68634. return a.x - b.x;
  68635. }
  68636. // find a bridge between vertices that connects hole with an outer ring and and link it
  68637. function eliminateHole(hole, outerNode) {
  68638. outerNode = findHoleBridge(hole, outerNode);
  68639. if (outerNode) {
  68640. var b = splitPolygon(outerNode, hole);
  68641. filterPoints(b, b.next);
  68642. }
  68643. }
  68644. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  68645. function findHoleBridge(hole, outerNode) {
  68646. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  68647. // find a segment intersected by a ray from the hole's leftmost point to the left;
  68648. // segment's endpoint with lesser x will be potential connection point
  68649. do {
  68650. if (hy <= p.y && hy >= p.next.y) {
  68651. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  68652. if (x <= hx && x > qx) {
  68653. qx = x;
  68654. if (x === hx) {
  68655. if (hy === p.y)
  68656. return p;
  68657. if (hy === p.next.y)
  68658. return p.next;
  68659. }
  68660. m = p.x < p.next.x ? p : p.next;
  68661. }
  68662. }
  68663. p = p.next;
  68664. } while (p !== outerNode);
  68665. if (!m)
  68666. return null;
  68667. if (hx === qx)
  68668. return m.prev; // hole touches outer segment; pick lower endpoint
  68669. // look for points inside the triangle of hole point, segment intersection and endpoint;
  68670. // if there are no points found, we have a valid connection;
  68671. // otherwise choose the point of the minimum angle with the ray as connection point
  68672. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  68673. p = m.next;
  68674. while (p !== stop) {
  68675. if (hx >= p.x &&
  68676. p.x >= mx &&
  68677. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  68678. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  68679. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  68680. m = p;
  68681. tanMin = tan;
  68682. }
  68683. }
  68684. p = p.next;
  68685. }
  68686. return m;
  68687. }
  68688. // interlink polygon nodes in z-order
  68689. function indexCurve(start, minX, minY, size) {
  68690. var p = start;
  68691. do {
  68692. if (p.z === null)
  68693. p.z = zOrder(p.x, p.y, minX, minY, size);
  68694. p.prevZ = p.prev;
  68695. p.nextZ = p.next;
  68696. p = p.next;
  68697. } while (p !== start);
  68698. p.prevZ.nextZ = null;
  68699. p.prevZ = null;
  68700. sortLinked(p);
  68701. }
  68702. // Simon Tatham's linked list merge sort algorithm
  68703. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  68704. function sortLinked(list) {
  68705. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  68706. do {
  68707. p = list;
  68708. list = null;
  68709. tail = null;
  68710. numMerges = 0;
  68711. while (p) {
  68712. numMerges++;
  68713. q = p;
  68714. pSize = 0;
  68715. for (i = 0; i < inSize; i++) {
  68716. pSize++;
  68717. q = q.nextZ;
  68718. if (!q)
  68719. break;
  68720. }
  68721. qSize = inSize;
  68722. while (pSize > 0 || (qSize > 0 && q)) {
  68723. if (pSize === 0) {
  68724. e = q;
  68725. q = q.nextZ;
  68726. qSize--;
  68727. }
  68728. else if (qSize === 0 || !q) {
  68729. e = p;
  68730. p = p.nextZ;
  68731. pSize--;
  68732. }
  68733. else if (p.z <= q.z) {
  68734. e = p;
  68735. p = p.nextZ;
  68736. pSize--;
  68737. }
  68738. else {
  68739. e = q;
  68740. q = q.nextZ;
  68741. qSize--;
  68742. }
  68743. if (tail)
  68744. tail.nextZ = e;
  68745. else
  68746. list = e;
  68747. e.prevZ = tail;
  68748. tail = e;
  68749. }
  68750. p = q;
  68751. }
  68752. tail.nextZ = null;
  68753. inSize *= 2;
  68754. } while (numMerges > 1);
  68755. return list;
  68756. }
  68757. // z-order of a point given coords and size of the data bounding box
  68758. function zOrder(x, y, minX, minY, size) {
  68759. // coords are transformed into non-negative 15-bit integer range
  68760. x = 32767 * (x - minX) / size;
  68761. y = 32767 * (y - minY) / size;
  68762. x = (x | (x << 8)) & 0x00FF00FF;
  68763. x = (x | (x << 4)) & 0x0F0F0F0F;
  68764. x = (x | (x << 2)) & 0x33333333;
  68765. x = (x | (x << 1)) & 0x55555555;
  68766. y = (y | (y << 8)) & 0x00FF00FF;
  68767. y = (y | (y << 4)) & 0x0F0F0F0F;
  68768. y = (y | (y << 2)) & 0x33333333;
  68769. y = (y | (y << 1)) & 0x55555555;
  68770. return x | (y << 1);
  68771. }
  68772. // find the leftmost node of a polygon ring
  68773. function getLeftmost(start) {
  68774. var p = start, leftmost = start;
  68775. do {
  68776. if (p.x < leftmost.x)
  68777. leftmost = p;
  68778. p = p.next;
  68779. } while (p !== start);
  68780. return leftmost;
  68781. }
  68782. // check if a point lies within a convex triangle
  68783. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  68784. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  68785. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  68786. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  68787. }
  68788. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  68789. function isValidDiagonal(a, b) {
  68790. return a.next.i !== b.i &&
  68791. a.prev.i !== b.i &&
  68792. !intersectsPolygon(a, b) &&
  68793. locallyInside(a, b) &&
  68794. locallyInside(b, a) &&
  68795. middleInside(a, b);
  68796. }
  68797. // signed area of a triangle
  68798. function area(p, q, r) {
  68799. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  68800. }
  68801. // check if two points are equal
  68802. function equals(p1, p2) {
  68803. return p1.x === p2.x && p1.y === p2.y;
  68804. }
  68805. // check if two segments intersect
  68806. function intersects(p1, q1, p2, q2) {
  68807. if ((equals(p1, q1) && equals(p2, q2)) ||
  68808. (equals(p1, q2) && equals(p2, q1)))
  68809. return true;
  68810. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  68811. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  68812. }
  68813. // check if a polygon diagonal intersects any polygon segments
  68814. function intersectsPolygon(a, b) {
  68815. var p = a;
  68816. do {
  68817. if (p.i !== a.i &&
  68818. p.next.i !== a.i &&
  68819. p.i !== b.i &&
  68820. p.next.i !== b.i &&
  68821. intersects(p, p.next, a, b))
  68822. return true;
  68823. p = p.next;
  68824. } while (p !== a);
  68825. return false;
  68826. }
  68827. // check if a polygon diagonal is locally inside the polygon
  68828. function locallyInside(a, b) {
  68829. return area(a.prev, a, a.next) < 0
  68830. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  68831. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  68832. }
  68833. // check if the middle point of a polygon diagonal is inside the polygon
  68834. function middleInside(a, b) {
  68835. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  68836. do {
  68837. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  68838. inside = !inside;
  68839. p = p.next;
  68840. } while (p !== a);
  68841. return inside;
  68842. }
  68843. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  68844. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  68845. function splitPolygon(a, b) {
  68846. 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;
  68847. a.next = b;
  68848. b.prev = a;
  68849. a2.next = an;
  68850. an.prev = a2;
  68851. b2.next = a2;
  68852. a2.prev = b2;
  68853. bp.next = b2;
  68854. b2.prev = bp;
  68855. return b2;
  68856. }
  68857. // create a node and optionally link it with previous one (in a circular doubly linked list)
  68858. function insertNode(i, x, y, last) {
  68859. var p = new Node(i, x, y);
  68860. if (!last) {
  68861. p.prev = p;
  68862. p.next = p;
  68863. }
  68864. else {
  68865. p.next = last.next;
  68866. p.prev = last;
  68867. last.next.prev = p;
  68868. last.next = p;
  68869. }
  68870. return p;
  68871. }
  68872. function removeNode(p) {
  68873. p.next.prev = p.prev;
  68874. p.prev.next = p.next;
  68875. if (p.prevZ)
  68876. p.prevZ.nextZ = p.nextZ;
  68877. if (p.nextZ)
  68878. p.nextZ.prevZ = p.prevZ;
  68879. }
  68880. /**
  68881. * return a percentage difference between the polygon area and its triangulation area;
  68882. * used to verify correctness of triangulation
  68883. */
  68884. function deviation(data, holeIndices, dim, triangles) {
  68885. var hasHoles = holeIndices && holeIndices.length;
  68886. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  68887. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  68888. if (hasHoles) {
  68889. for (var i = 0, len = holeIndices.length; i < len; i++) {
  68890. var start = holeIndices[i] * dim;
  68891. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  68892. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  68893. }
  68894. }
  68895. var trianglesArea = 0;
  68896. for (i = 0; i < triangles.length; i += 3) {
  68897. var a = triangles[i] * dim;
  68898. var b = triangles[i + 1] * dim;
  68899. var c = triangles[i + 2] * dim;
  68900. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  68901. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  68902. }
  68903. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  68904. }
  68905. Earcut.deviation = deviation;
  68906. ;
  68907. function signedArea(data, start, end, dim) {
  68908. var sum = 0;
  68909. for (var i = start, j = end - dim; i < end; i += dim) {
  68910. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  68911. j = i;
  68912. }
  68913. return sum;
  68914. }
  68915. /**
  68916. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  68917. */
  68918. function flatten(data) {
  68919. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  68920. for (var i = 0; i < data.length; i++) {
  68921. for (var j = 0; j < data[i].length; j++) {
  68922. for (var d = 0; d < dim; d++)
  68923. result.vertices.push(data[i][j][d]);
  68924. }
  68925. if (i > 0) {
  68926. holeIndex += data[i - 1].length;
  68927. result.holes.push(holeIndex);
  68928. }
  68929. }
  68930. return result;
  68931. }
  68932. Earcut.flatten = flatten;
  68933. ;
  68934. })(Earcut || (Earcut = {}));
  68935. //# sourceMappingURL=babylon.earcut.js.map
  68936. var BABYLON;
  68937. (function (BABYLON) {
  68938. var IndexedVector2 = /** @class */ (function (_super) {
  68939. __extends(IndexedVector2, _super);
  68940. function IndexedVector2(original, index) {
  68941. var _this = _super.call(this, original.x, original.y) || this;
  68942. _this.index = index;
  68943. return _this;
  68944. }
  68945. return IndexedVector2;
  68946. }(BABYLON.Vector2));
  68947. var PolygonPoints = /** @class */ (function () {
  68948. function PolygonPoints() {
  68949. this.elements = new Array();
  68950. }
  68951. PolygonPoints.prototype.add = function (originalPoints) {
  68952. var _this = this;
  68953. var result = new Array();
  68954. originalPoints.forEach(function (point) {
  68955. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  68956. var newPoint = new IndexedVector2(point, _this.elements.length);
  68957. result.push(newPoint);
  68958. _this.elements.push(newPoint);
  68959. }
  68960. });
  68961. return result;
  68962. };
  68963. PolygonPoints.prototype.computeBounds = function () {
  68964. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  68965. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  68966. this.elements.forEach(function (point) {
  68967. // x
  68968. if (point.x < lmin.x) {
  68969. lmin.x = point.x;
  68970. }
  68971. else if (point.x > lmax.x) {
  68972. lmax.x = point.x;
  68973. }
  68974. // y
  68975. if (point.y < lmin.y) {
  68976. lmin.y = point.y;
  68977. }
  68978. else if (point.y > lmax.y) {
  68979. lmax.y = point.y;
  68980. }
  68981. });
  68982. return {
  68983. min: lmin,
  68984. max: lmax,
  68985. width: lmax.x - lmin.x,
  68986. height: lmax.y - lmin.y
  68987. };
  68988. };
  68989. return PolygonPoints;
  68990. }());
  68991. var Polygon = /** @class */ (function () {
  68992. function Polygon() {
  68993. }
  68994. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  68995. return [
  68996. new BABYLON.Vector2(xmin, ymin),
  68997. new BABYLON.Vector2(xmax, ymin),
  68998. new BABYLON.Vector2(xmax, ymax),
  68999. new BABYLON.Vector2(xmin, ymax)
  69000. ];
  69001. };
  69002. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  69003. if (cx === void 0) { cx = 0; }
  69004. if (cy === void 0) { cy = 0; }
  69005. if (numberOfSides === void 0) { numberOfSides = 32; }
  69006. var result = new Array();
  69007. var angle = 0;
  69008. var increment = (Math.PI * 2) / numberOfSides;
  69009. for (var i = 0; i < numberOfSides; i++) {
  69010. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  69011. angle -= increment;
  69012. }
  69013. return result;
  69014. };
  69015. Polygon.Parse = function (input) {
  69016. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  69017. var i, result = [];
  69018. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  69019. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  69020. }
  69021. return result;
  69022. };
  69023. Polygon.StartingAt = function (x, y) {
  69024. return BABYLON.Path2.StartingAt(x, y);
  69025. };
  69026. return Polygon;
  69027. }());
  69028. BABYLON.Polygon = Polygon;
  69029. var PolygonMeshBuilder = /** @class */ (function () {
  69030. function PolygonMeshBuilder(name, contours, scene) {
  69031. this._points = new PolygonPoints();
  69032. this._outlinepoints = new PolygonPoints();
  69033. this._holes = new Array();
  69034. this._epoints = new Array();
  69035. this._eholes = new Array();
  69036. this._name = name;
  69037. this._scene = scene;
  69038. var points;
  69039. if (contours instanceof BABYLON.Path2) {
  69040. points = contours.getPoints();
  69041. }
  69042. else {
  69043. points = contours;
  69044. }
  69045. this._addToepoint(points);
  69046. this._points.add(points);
  69047. this._outlinepoints.add(points);
  69048. }
  69049. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  69050. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  69051. var p = points_1[_i];
  69052. this._epoints.push(p.x, p.y);
  69053. }
  69054. };
  69055. PolygonMeshBuilder.prototype.addHole = function (hole) {
  69056. this._points.add(hole);
  69057. var holepoints = new PolygonPoints();
  69058. holepoints.add(hole);
  69059. this._holes.push(holepoints);
  69060. this._eholes.push(this._epoints.length / 2);
  69061. this._addToepoint(hole);
  69062. return this;
  69063. };
  69064. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  69065. var _this = this;
  69066. if (updatable === void 0) { updatable = false; }
  69067. if (depth === void 0) { depth = 0; }
  69068. var result = new BABYLON.Mesh(this._name, this._scene);
  69069. var normals = new Array();
  69070. var positions = new Array();
  69071. var uvs = new Array();
  69072. var bounds = this._points.computeBounds();
  69073. this._points.elements.forEach(function (p) {
  69074. normals.push(0, 1.0, 0);
  69075. positions.push(p.x, 0, p.y);
  69076. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  69077. });
  69078. var indices = new Array();
  69079. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  69080. for (var i = 0; i < res.length; i++) {
  69081. indices.push(res[i]);
  69082. }
  69083. if (depth > 0) {
  69084. var positionscount = (positions.length / 3); //get the current pointcount
  69085. this._points.elements.forEach(function (p) {
  69086. normals.push(0, -1.0, 0);
  69087. positions.push(p.x, -depth, p.y);
  69088. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  69089. });
  69090. var totalCount = indices.length;
  69091. for (var i = 0; i < totalCount; i += 3) {
  69092. var i0 = indices[i + 0];
  69093. var i1 = indices[i + 1];
  69094. var i2 = indices[i + 2];
  69095. indices.push(i2 + positionscount);
  69096. indices.push(i1 + positionscount);
  69097. indices.push(i0 + positionscount);
  69098. }
  69099. //Add the sides
  69100. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  69101. this._holes.forEach(function (hole) {
  69102. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  69103. });
  69104. }
  69105. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  69106. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  69107. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  69108. result.setIndices(indices);
  69109. return result;
  69110. };
  69111. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  69112. var StartIndex = positions.length / 3;
  69113. var ulength = 0;
  69114. for (var i = 0; i < points.elements.length; i++) {
  69115. var p = points.elements[i];
  69116. var p1;
  69117. if ((i + 1) > points.elements.length - 1) {
  69118. p1 = points.elements[0];
  69119. }
  69120. else {
  69121. p1 = points.elements[i + 1];
  69122. }
  69123. positions.push(p.x, 0, p.y);
  69124. positions.push(p.x, -depth, p.y);
  69125. positions.push(p1.x, 0, p1.y);
  69126. positions.push(p1.x, -depth, p1.y);
  69127. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  69128. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  69129. var v3 = v2.subtract(v1);
  69130. var v4 = new BABYLON.Vector3(0, 1, 0);
  69131. var vn = BABYLON.Vector3.Cross(v3, v4);
  69132. vn = vn.normalize();
  69133. uvs.push(ulength / bounds.width, 0);
  69134. uvs.push(ulength / bounds.width, 1);
  69135. ulength += v3.length();
  69136. uvs.push((ulength / bounds.width), 0);
  69137. uvs.push((ulength / bounds.width), 1);
  69138. if (!flip) {
  69139. normals.push(-vn.x, -vn.y, -vn.z);
  69140. normals.push(-vn.x, -vn.y, -vn.z);
  69141. normals.push(-vn.x, -vn.y, -vn.z);
  69142. normals.push(-vn.x, -vn.y, -vn.z);
  69143. indices.push(StartIndex);
  69144. indices.push(StartIndex + 1);
  69145. indices.push(StartIndex + 2);
  69146. indices.push(StartIndex + 1);
  69147. indices.push(StartIndex + 3);
  69148. indices.push(StartIndex + 2);
  69149. }
  69150. else {
  69151. normals.push(vn.x, vn.y, vn.z);
  69152. normals.push(vn.x, vn.y, vn.z);
  69153. normals.push(vn.x, vn.y, vn.z);
  69154. normals.push(vn.x, vn.y, vn.z);
  69155. indices.push(StartIndex);
  69156. indices.push(StartIndex + 2);
  69157. indices.push(StartIndex + 1);
  69158. indices.push(StartIndex + 1);
  69159. indices.push(StartIndex + 2);
  69160. indices.push(StartIndex + 3);
  69161. }
  69162. StartIndex += 4;
  69163. }
  69164. ;
  69165. };
  69166. return PolygonMeshBuilder;
  69167. }());
  69168. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  69169. })(BABYLON || (BABYLON = {}));
  69170. //# sourceMappingURL=babylon.polygonMesh.js.map
  69171. var BABYLON;
  69172. (function (BABYLON) {
  69173. // Unique ID when we import meshes from Babylon to CSG
  69174. var currentCSGMeshId = 0;
  69175. // # class Vertex
  69176. // Represents a vertex of a polygon. Use your own vertex class instead of this
  69177. // one to provide additional features like texture coordinates and vertex
  69178. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  69179. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  69180. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  69181. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  69182. // is not used anywhere else.
  69183. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  69184. var Vertex = /** @class */ (function () {
  69185. function Vertex(pos, normal, uv) {
  69186. this.pos = pos;
  69187. this.normal = normal;
  69188. this.uv = uv;
  69189. }
  69190. Vertex.prototype.clone = function () {
  69191. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  69192. };
  69193. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  69194. // orientation of a polygon is flipped.
  69195. Vertex.prototype.flip = function () {
  69196. this.normal = this.normal.scale(-1);
  69197. };
  69198. // Create a new vertex between this vertex and `other` by linearly
  69199. // interpolating all properties using a parameter of `t`. Subclasses should
  69200. // override this to interpolate additional properties.
  69201. Vertex.prototype.interpolate = function (other, t) {
  69202. 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));
  69203. };
  69204. return Vertex;
  69205. }());
  69206. // # class Plane
  69207. // Represents a plane in 3D space.
  69208. var Plane = /** @class */ (function () {
  69209. function Plane(normal, w) {
  69210. this.normal = normal;
  69211. this.w = w;
  69212. }
  69213. Plane.FromPoints = function (a, b, c) {
  69214. var v0 = c.subtract(a);
  69215. var v1 = b.subtract(a);
  69216. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  69217. return null;
  69218. }
  69219. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  69220. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  69221. };
  69222. Plane.prototype.clone = function () {
  69223. return new Plane(this.normal.clone(), this.w);
  69224. };
  69225. Plane.prototype.flip = function () {
  69226. this.normal.scaleInPlace(-1);
  69227. this.w = -this.w;
  69228. };
  69229. // Split `polygon` by this plane if needed, then put the polygon or polygon
  69230. // fragments in the appropriate lists. Coplanar polygons go into either
  69231. // `coplanarFront` or `coplanarBack` depending on their orientation with
  69232. // respect to this plane. Polygons in front or in back of this plane go into
  69233. // either `front` or `back`.
  69234. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  69235. var COPLANAR = 0;
  69236. var FRONT = 1;
  69237. var BACK = 2;
  69238. var SPANNING = 3;
  69239. // Classify each point as well as the entire polygon into one of the above
  69240. // four classes.
  69241. var polygonType = 0;
  69242. var types = [];
  69243. var i;
  69244. var t;
  69245. for (i = 0; i < polygon.vertices.length; i++) {
  69246. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  69247. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  69248. polygonType |= type;
  69249. types.push(type);
  69250. }
  69251. // Put the polygon in the correct list, splitting it when necessary.
  69252. switch (polygonType) {
  69253. case COPLANAR:
  69254. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  69255. break;
  69256. case FRONT:
  69257. front.push(polygon);
  69258. break;
  69259. case BACK:
  69260. back.push(polygon);
  69261. break;
  69262. case SPANNING:
  69263. var f = [], b = [];
  69264. for (i = 0; i < polygon.vertices.length; i++) {
  69265. var j = (i + 1) % polygon.vertices.length;
  69266. var ti = types[i], tj = types[j];
  69267. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  69268. if (ti !== BACK)
  69269. f.push(vi);
  69270. if (ti !== FRONT)
  69271. b.push(ti !== BACK ? vi.clone() : vi);
  69272. if ((ti | tj) === SPANNING) {
  69273. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  69274. var v = vi.interpolate(vj, t);
  69275. f.push(v);
  69276. b.push(v.clone());
  69277. }
  69278. }
  69279. var poly;
  69280. if (f.length >= 3) {
  69281. poly = new Polygon(f, polygon.shared);
  69282. if (poly.plane)
  69283. front.push(poly);
  69284. }
  69285. if (b.length >= 3) {
  69286. poly = new Polygon(b, polygon.shared);
  69287. if (poly.plane)
  69288. back.push(poly);
  69289. }
  69290. break;
  69291. }
  69292. };
  69293. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  69294. // point is on the plane.
  69295. Plane.EPSILON = 1e-5;
  69296. return Plane;
  69297. }());
  69298. // # class Polygon
  69299. // Represents a convex polygon. The vertices used to initialize a polygon must
  69300. // be coplanar and form a convex loop.
  69301. //
  69302. // Each convex polygon has a `shared` property, which is shared between all
  69303. // polygons that are clones of each other or were split from the same polygon.
  69304. // This can be used to define per-polygon properties (such as surface color).
  69305. var Polygon = /** @class */ (function () {
  69306. function Polygon(vertices, shared) {
  69307. this.vertices = vertices;
  69308. this.shared = shared;
  69309. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  69310. }
  69311. Polygon.prototype.clone = function () {
  69312. var vertices = this.vertices.map(function (v) { return v.clone(); });
  69313. return new Polygon(vertices, this.shared);
  69314. };
  69315. Polygon.prototype.flip = function () {
  69316. this.vertices.reverse().map(function (v) { v.flip(); });
  69317. this.plane.flip();
  69318. };
  69319. return Polygon;
  69320. }());
  69321. // # class Node
  69322. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  69323. // by picking a polygon to split along. That polygon (and all other coplanar
  69324. // polygons) are added directly to that node and the other polygons are added to
  69325. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  69326. // no distinction between internal and leaf nodes.
  69327. var Node = /** @class */ (function () {
  69328. function Node(polygons) {
  69329. this.plane = null;
  69330. this.front = null;
  69331. this.back = null;
  69332. this.polygons = new Array();
  69333. if (polygons) {
  69334. this.build(polygons);
  69335. }
  69336. }
  69337. Node.prototype.clone = function () {
  69338. var node = new Node();
  69339. node.plane = this.plane && this.plane.clone();
  69340. node.front = this.front && this.front.clone();
  69341. node.back = this.back && this.back.clone();
  69342. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  69343. return node;
  69344. };
  69345. // Convert solid space to empty space and empty space to solid space.
  69346. Node.prototype.invert = function () {
  69347. for (var i = 0; i < this.polygons.length; i++) {
  69348. this.polygons[i].flip();
  69349. }
  69350. if (this.plane) {
  69351. this.plane.flip();
  69352. }
  69353. if (this.front) {
  69354. this.front.invert();
  69355. }
  69356. if (this.back) {
  69357. this.back.invert();
  69358. }
  69359. var temp = this.front;
  69360. this.front = this.back;
  69361. this.back = temp;
  69362. };
  69363. // Recursively remove all polygons in `polygons` that are inside this BSP
  69364. // tree.
  69365. Node.prototype.clipPolygons = function (polygons) {
  69366. if (!this.plane)
  69367. return polygons.slice();
  69368. var front = new Array(), back = new Array();
  69369. for (var i = 0; i < polygons.length; i++) {
  69370. this.plane.splitPolygon(polygons[i], front, back, front, back);
  69371. }
  69372. if (this.front) {
  69373. front = this.front.clipPolygons(front);
  69374. }
  69375. if (this.back) {
  69376. back = this.back.clipPolygons(back);
  69377. }
  69378. else {
  69379. back = [];
  69380. }
  69381. return front.concat(back);
  69382. };
  69383. // Remove all polygons in this BSP tree that are inside the other BSP tree
  69384. // `bsp`.
  69385. Node.prototype.clipTo = function (bsp) {
  69386. this.polygons = bsp.clipPolygons(this.polygons);
  69387. if (this.front)
  69388. this.front.clipTo(bsp);
  69389. if (this.back)
  69390. this.back.clipTo(bsp);
  69391. };
  69392. // Return a list of all polygons in this BSP tree.
  69393. Node.prototype.allPolygons = function () {
  69394. var polygons = this.polygons.slice();
  69395. if (this.front)
  69396. polygons = polygons.concat(this.front.allPolygons());
  69397. if (this.back)
  69398. polygons = polygons.concat(this.back.allPolygons());
  69399. return polygons;
  69400. };
  69401. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  69402. // new polygons are filtered down to the bottom of the tree and become new
  69403. // nodes there. Each set of polygons is partitioned using the first polygon
  69404. // (no heuristic is used to pick a good split).
  69405. Node.prototype.build = function (polygons) {
  69406. if (!polygons.length)
  69407. return;
  69408. if (!this.plane)
  69409. this.plane = polygons[0].plane.clone();
  69410. var front = new Array(), back = new Array();
  69411. for (var i = 0; i < polygons.length; i++) {
  69412. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  69413. }
  69414. if (front.length) {
  69415. if (!this.front)
  69416. this.front = new Node();
  69417. this.front.build(front);
  69418. }
  69419. if (back.length) {
  69420. if (!this.back)
  69421. this.back = new Node();
  69422. this.back.build(back);
  69423. }
  69424. };
  69425. return Node;
  69426. }());
  69427. var CSG = /** @class */ (function () {
  69428. function CSG() {
  69429. this.polygons = new Array();
  69430. }
  69431. // Convert BABYLON.Mesh to BABYLON.CSG
  69432. CSG.FromMesh = function (mesh) {
  69433. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  69434. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  69435. if (mesh instanceof BABYLON.Mesh) {
  69436. mesh.computeWorldMatrix(true);
  69437. matrix = mesh.getWorldMatrix();
  69438. meshPosition = mesh.position.clone();
  69439. meshRotation = mesh.rotation.clone();
  69440. if (mesh.rotationQuaternion) {
  69441. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  69442. }
  69443. meshScaling = mesh.scaling.clone();
  69444. }
  69445. else {
  69446. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  69447. }
  69448. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  69449. var subMeshes = mesh.subMeshes;
  69450. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  69451. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  69452. vertices = [];
  69453. for (var j = 0; j < 3; j++) {
  69454. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  69455. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  69456. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  69457. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  69458. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  69459. vertex = new Vertex(position, normal, uv);
  69460. vertices.push(vertex);
  69461. }
  69462. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  69463. // To handle the case of degenerated triangle
  69464. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  69465. if (polygon.plane)
  69466. polygons.push(polygon);
  69467. }
  69468. }
  69469. var csg = CSG.FromPolygons(polygons);
  69470. csg.matrix = matrix;
  69471. csg.position = meshPosition;
  69472. csg.rotation = meshRotation;
  69473. csg.scaling = meshScaling;
  69474. csg.rotationQuaternion = meshRotationQuaternion;
  69475. currentCSGMeshId++;
  69476. return csg;
  69477. };
  69478. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  69479. CSG.FromPolygons = function (polygons) {
  69480. var csg = new CSG();
  69481. csg.polygons = polygons;
  69482. return csg;
  69483. };
  69484. CSG.prototype.clone = function () {
  69485. var csg = new CSG();
  69486. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  69487. csg.copyTransformAttributes(this);
  69488. return csg;
  69489. };
  69490. CSG.prototype.union = function (csg) {
  69491. var a = new Node(this.clone().polygons);
  69492. var b = new Node(csg.clone().polygons);
  69493. a.clipTo(b);
  69494. b.clipTo(a);
  69495. b.invert();
  69496. b.clipTo(a);
  69497. b.invert();
  69498. a.build(b.allPolygons());
  69499. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  69500. };
  69501. CSG.prototype.unionInPlace = function (csg) {
  69502. var a = new Node(this.polygons);
  69503. var b = new Node(csg.polygons);
  69504. a.clipTo(b);
  69505. b.clipTo(a);
  69506. b.invert();
  69507. b.clipTo(a);
  69508. b.invert();
  69509. a.build(b.allPolygons());
  69510. this.polygons = a.allPolygons();
  69511. };
  69512. CSG.prototype.subtract = function (csg) {
  69513. var a = new Node(this.clone().polygons);
  69514. var b = new Node(csg.clone().polygons);
  69515. a.invert();
  69516. a.clipTo(b);
  69517. b.clipTo(a);
  69518. b.invert();
  69519. b.clipTo(a);
  69520. b.invert();
  69521. a.build(b.allPolygons());
  69522. a.invert();
  69523. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  69524. };
  69525. CSG.prototype.subtractInPlace = function (csg) {
  69526. var a = new Node(this.polygons);
  69527. var b = new Node(csg.polygons);
  69528. a.invert();
  69529. a.clipTo(b);
  69530. b.clipTo(a);
  69531. b.invert();
  69532. b.clipTo(a);
  69533. b.invert();
  69534. a.build(b.allPolygons());
  69535. a.invert();
  69536. this.polygons = a.allPolygons();
  69537. };
  69538. CSG.prototype.intersect = function (csg) {
  69539. var a = new Node(this.clone().polygons);
  69540. var b = new Node(csg.clone().polygons);
  69541. a.invert();
  69542. b.clipTo(a);
  69543. b.invert();
  69544. a.clipTo(b);
  69545. b.clipTo(a);
  69546. a.build(b.allPolygons());
  69547. a.invert();
  69548. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  69549. };
  69550. CSG.prototype.intersectInPlace = function (csg) {
  69551. var a = new Node(this.polygons);
  69552. var b = new Node(csg.polygons);
  69553. a.invert();
  69554. b.clipTo(a);
  69555. b.invert();
  69556. a.clipTo(b);
  69557. b.clipTo(a);
  69558. a.build(b.allPolygons());
  69559. a.invert();
  69560. this.polygons = a.allPolygons();
  69561. };
  69562. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  69563. // not modified.
  69564. CSG.prototype.inverse = function () {
  69565. var csg = this.clone();
  69566. csg.inverseInPlace();
  69567. return csg;
  69568. };
  69569. CSG.prototype.inverseInPlace = function () {
  69570. this.polygons.map(function (p) { p.flip(); });
  69571. };
  69572. // This is used to keep meshes transformations so they can be restored
  69573. // when we build back a Babylon Mesh
  69574. // NB : All CSG operations are performed in world coordinates
  69575. CSG.prototype.copyTransformAttributes = function (csg) {
  69576. this.matrix = csg.matrix;
  69577. this.position = csg.position;
  69578. this.rotation = csg.rotation;
  69579. this.scaling = csg.scaling;
  69580. this.rotationQuaternion = csg.rotationQuaternion;
  69581. return this;
  69582. };
  69583. // Build Raw mesh from CSG
  69584. // Coordinates here are in world space
  69585. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  69586. var matrix = this.matrix.clone();
  69587. matrix.invert();
  69588. 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;
  69589. if (keepSubMeshes) {
  69590. // Sort Polygons, since subMeshes are indices range
  69591. polygons.sort(function (a, b) {
  69592. if (a.shared.meshId === b.shared.meshId) {
  69593. return a.shared.subMeshId - b.shared.subMeshId;
  69594. }
  69595. else {
  69596. return a.shared.meshId - b.shared.meshId;
  69597. }
  69598. });
  69599. }
  69600. for (var i = 0, il = polygons.length; i < il; i++) {
  69601. polygon = polygons[i];
  69602. // Building SubMeshes
  69603. if (!subMesh_dict[polygon.shared.meshId]) {
  69604. subMesh_dict[polygon.shared.meshId] = {};
  69605. }
  69606. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  69607. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  69608. indexStart: +Infinity,
  69609. indexEnd: -Infinity,
  69610. materialIndex: polygon.shared.materialIndex
  69611. };
  69612. }
  69613. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  69614. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  69615. polygonIndices[0] = 0;
  69616. polygonIndices[1] = j - 1;
  69617. polygonIndices[2] = j;
  69618. for (var k = 0; k < 3; k++) {
  69619. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  69620. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  69621. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  69622. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  69623. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  69624. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  69625. // Check if 2 points can be merged
  69626. if (!(typeof vertex_idx !== 'undefined' &&
  69627. normals[vertex_idx * 3] === localNormal.x &&
  69628. normals[vertex_idx * 3 + 1] === localNormal.y &&
  69629. normals[vertex_idx * 3 + 2] === localNormal.z &&
  69630. uvs[vertex_idx * 2] === uv.x &&
  69631. uvs[vertex_idx * 2 + 1] === uv.y)) {
  69632. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  69633. uvs.push(uv.x, uv.y);
  69634. normals.push(normal.x, normal.y, normal.z);
  69635. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  69636. }
  69637. indices.push(vertex_idx);
  69638. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  69639. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  69640. currentIndex++;
  69641. }
  69642. }
  69643. }
  69644. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  69645. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  69646. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  69647. mesh.setIndices(indices, null);
  69648. if (keepSubMeshes) {
  69649. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  69650. var materialIndexOffset = 0, materialMaxIndex;
  69651. mesh.subMeshes = new Array();
  69652. for (var m in subMesh_dict) {
  69653. materialMaxIndex = -1;
  69654. for (var sm in subMesh_dict[m]) {
  69655. subMesh_obj = subMesh_dict[m][sm];
  69656. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  69657. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  69658. }
  69659. materialIndexOffset += ++materialMaxIndex;
  69660. }
  69661. }
  69662. return mesh;
  69663. };
  69664. // Build Mesh from CSG taking material and transforms into account
  69665. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  69666. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  69667. mesh.material = material;
  69668. mesh.position.copyFrom(this.position);
  69669. mesh.rotation.copyFrom(this.rotation);
  69670. if (this.rotationQuaternion) {
  69671. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  69672. }
  69673. mesh.scaling.copyFrom(this.scaling);
  69674. mesh.computeWorldMatrix(true);
  69675. return mesh;
  69676. };
  69677. return CSG;
  69678. }());
  69679. BABYLON.CSG = CSG;
  69680. })(BABYLON || (BABYLON = {}));
  69681. //# sourceMappingURL=babylon.csg.js.map
  69682. var BABYLON;
  69683. (function (BABYLON) {
  69684. var LensFlare = /** @class */ (function () {
  69685. function LensFlare(size, position, color, imgUrl, system) {
  69686. this.size = size;
  69687. this.position = position;
  69688. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  69689. this.color = color || new BABYLON.Color3(1, 1, 1);
  69690. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  69691. this._system = system;
  69692. system.lensFlares.push(this);
  69693. }
  69694. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  69695. return new LensFlare(size, position, color, imgUrl, system);
  69696. };
  69697. LensFlare.prototype.dispose = function () {
  69698. if (this.texture) {
  69699. this.texture.dispose();
  69700. }
  69701. // Remove from scene
  69702. var index = this._system.lensFlares.indexOf(this);
  69703. this._system.lensFlares.splice(index, 1);
  69704. };
  69705. ;
  69706. return LensFlare;
  69707. }());
  69708. BABYLON.LensFlare = LensFlare;
  69709. })(BABYLON || (BABYLON = {}));
  69710. //# sourceMappingURL=babylon.lensFlare.js.map
  69711. var BABYLON;
  69712. (function (BABYLON) {
  69713. var LensFlareSystem = /** @class */ (function () {
  69714. function LensFlareSystem(name, emitter, scene) {
  69715. this.name = name;
  69716. this.lensFlares = new Array();
  69717. this.borderLimit = 300;
  69718. this.viewportBorder = 0;
  69719. this.layerMask = 0x0FFFFFFF;
  69720. this._vertexBuffers = {};
  69721. this._isEnabled = true;
  69722. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  69723. this._emitter = emitter;
  69724. this.id = name;
  69725. scene.lensFlareSystems.push(this);
  69726. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  69727. var engine = scene.getEngine();
  69728. // VBO
  69729. var vertices = [];
  69730. vertices.push(1, 1);
  69731. vertices.push(-1, 1);
  69732. vertices.push(-1, -1);
  69733. vertices.push(1, -1);
  69734. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  69735. // Indices
  69736. var indices = [];
  69737. indices.push(0);
  69738. indices.push(1);
  69739. indices.push(2);
  69740. indices.push(0);
  69741. indices.push(2);
  69742. indices.push(3);
  69743. this._indexBuffer = engine.createIndexBuffer(indices);
  69744. // Effects
  69745. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  69746. }
  69747. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  69748. get: function () {
  69749. return this._isEnabled;
  69750. },
  69751. set: function (value) {
  69752. this._isEnabled = value;
  69753. },
  69754. enumerable: true,
  69755. configurable: true
  69756. });
  69757. LensFlareSystem.prototype.getScene = function () {
  69758. return this._scene;
  69759. };
  69760. LensFlareSystem.prototype.getEmitter = function () {
  69761. return this._emitter;
  69762. };
  69763. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  69764. this._emitter = newEmitter;
  69765. };
  69766. LensFlareSystem.prototype.getEmitterPosition = function () {
  69767. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  69768. };
  69769. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  69770. var position = this.getEmitterPosition();
  69771. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  69772. this._positionX = position.x;
  69773. this._positionY = position.y;
  69774. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  69775. if (this.viewportBorder > 0) {
  69776. globalViewport.x -= this.viewportBorder;
  69777. globalViewport.y -= this.viewportBorder;
  69778. globalViewport.width += this.viewportBorder * 2;
  69779. globalViewport.height += this.viewportBorder * 2;
  69780. position.x += this.viewportBorder;
  69781. position.y += this.viewportBorder;
  69782. this._positionX += this.viewportBorder;
  69783. this._positionY += this.viewportBorder;
  69784. }
  69785. if (position.z > 0) {
  69786. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  69787. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  69788. return true;
  69789. }
  69790. return true;
  69791. }
  69792. return false;
  69793. };
  69794. LensFlareSystem.prototype._isVisible = function () {
  69795. if (!this._isEnabled || !this._scene.activeCamera) {
  69796. return false;
  69797. }
  69798. var emitterPosition = this.getEmitterPosition();
  69799. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  69800. var distance = direction.length();
  69801. direction.normalize();
  69802. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  69803. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  69804. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  69805. };
  69806. LensFlareSystem.prototype.render = function () {
  69807. if (!this._effect.isReady() || !this._scene.activeCamera)
  69808. return false;
  69809. var engine = this._scene.getEngine();
  69810. var viewport = this._scene.activeCamera.viewport;
  69811. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  69812. // Position
  69813. if (!this.computeEffectivePosition(globalViewport)) {
  69814. return false;
  69815. }
  69816. // Visibility
  69817. if (!this._isVisible()) {
  69818. return false;
  69819. }
  69820. // Intensity
  69821. var awayX;
  69822. var awayY;
  69823. if (this._positionX < this.borderLimit + globalViewport.x) {
  69824. awayX = this.borderLimit + globalViewport.x - this._positionX;
  69825. }
  69826. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  69827. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  69828. }
  69829. else {
  69830. awayX = 0;
  69831. }
  69832. if (this._positionY < this.borderLimit + globalViewport.y) {
  69833. awayY = this.borderLimit + globalViewport.y - this._positionY;
  69834. }
  69835. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  69836. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  69837. }
  69838. else {
  69839. awayY = 0;
  69840. }
  69841. var away = (awayX > awayY) ? awayX : awayY;
  69842. away -= this.viewportBorder;
  69843. if (away > this.borderLimit) {
  69844. away = this.borderLimit;
  69845. }
  69846. var intensity = 1.0 - (away / this.borderLimit);
  69847. if (intensity < 0) {
  69848. return false;
  69849. }
  69850. if (intensity > 1.0) {
  69851. intensity = 1.0;
  69852. }
  69853. if (this.viewportBorder > 0) {
  69854. globalViewport.x += this.viewportBorder;
  69855. globalViewport.y += this.viewportBorder;
  69856. globalViewport.width -= this.viewportBorder * 2;
  69857. globalViewport.height -= this.viewportBorder * 2;
  69858. this._positionX -= this.viewportBorder;
  69859. this._positionY -= this.viewportBorder;
  69860. }
  69861. // Position
  69862. var centerX = globalViewport.x + globalViewport.width / 2;
  69863. var centerY = globalViewport.y + globalViewport.height / 2;
  69864. var distX = centerX - this._positionX;
  69865. var distY = centerY - this._positionY;
  69866. // Effects
  69867. engine.enableEffect(this._effect);
  69868. engine.setState(false);
  69869. engine.setDepthBuffer(false);
  69870. // VBOs
  69871. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  69872. // Flares
  69873. for (var index = 0; index < this.lensFlares.length; index++) {
  69874. var flare = this.lensFlares[index];
  69875. engine.setAlphaMode(flare.alphaMode);
  69876. var x = centerX - (distX * flare.position);
  69877. var y = centerY - (distY * flare.position);
  69878. var cw = flare.size;
  69879. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  69880. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  69881. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  69882. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  69883. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  69884. // Texture
  69885. this._effect.setTexture("textureSampler", flare.texture);
  69886. // Color
  69887. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  69888. // Draw order
  69889. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69890. }
  69891. engine.setDepthBuffer(true);
  69892. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  69893. return true;
  69894. };
  69895. LensFlareSystem.prototype.dispose = function () {
  69896. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69897. if (vertexBuffer) {
  69898. vertexBuffer.dispose();
  69899. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  69900. }
  69901. if (this._indexBuffer) {
  69902. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  69903. this._indexBuffer = null;
  69904. }
  69905. while (this.lensFlares.length) {
  69906. this.lensFlares[0].dispose();
  69907. }
  69908. // Remove from scene
  69909. var index = this._scene.lensFlareSystems.indexOf(this);
  69910. this._scene.lensFlareSystems.splice(index, 1);
  69911. };
  69912. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  69913. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  69914. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  69915. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  69916. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  69917. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  69918. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  69919. var parsedFlare = parsedLensFlareSystem.flares[index];
  69920. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  69921. }
  69922. return lensFlareSystem;
  69923. };
  69924. LensFlareSystem.prototype.serialize = function () {
  69925. var serializationObject = {};
  69926. serializationObject.id = this.id;
  69927. serializationObject.name = this.name;
  69928. serializationObject.emitterId = this.getEmitter().id;
  69929. serializationObject.borderLimit = this.borderLimit;
  69930. serializationObject.flares = [];
  69931. for (var index = 0; index < this.lensFlares.length; index++) {
  69932. var flare = this.lensFlares[index];
  69933. serializationObject.flares.push({
  69934. size: flare.size,
  69935. position: flare.position,
  69936. color: flare.color.asArray(),
  69937. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  69938. });
  69939. }
  69940. return serializationObject;
  69941. };
  69942. return LensFlareSystem;
  69943. }());
  69944. BABYLON.LensFlareSystem = LensFlareSystem;
  69945. })(BABYLON || (BABYLON = {}));
  69946. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  69947. var BABYLON;
  69948. (function (BABYLON) {
  69949. /**
  69950. * This is a holder class for the physics joint created by the physics plugin.
  69951. * It holds a set of functions to control the underlying joint.
  69952. */
  69953. var PhysicsJoint = /** @class */ (function () {
  69954. function PhysicsJoint(type, jointData) {
  69955. this.type = type;
  69956. this.jointData = jointData;
  69957. jointData.nativeParams = jointData.nativeParams || {};
  69958. }
  69959. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  69960. get: function () {
  69961. return this._physicsJoint;
  69962. },
  69963. set: function (newJoint) {
  69964. if (this._physicsJoint) {
  69965. //remove from the wolrd
  69966. }
  69967. this._physicsJoint = newJoint;
  69968. },
  69969. enumerable: true,
  69970. configurable: true
  69971. });
  69972. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  69973. set: function (physicsPlugin) {
  69974. this._physicsPlugin = physicsPlugin;
  69975. },
  69976. enumerable: true,
  69977. configurable: true
  69978. });
  69979. /**
  69980. * Execute a function that is physics-plugin specific.
  69981. * @param {Function} func the function that will be executed.
  69982. * It accepts two parameters: the physics world and the physics joint.
  69983. */
  69984. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  69985. func(this._physicsPlugin.world, this._physicsJoint);
  69986. };
  69987. //TODO check if the native joints are the same
  69988. //Joint Types
  69989. PhysicsJoint.DistanceJoint = 0;
  69990. PhysicsJoint.HingeJoint = 1;
  69991. PhysicsJoint.BallAndSocketJoint = 2;
  69992. PhysicsJoint.WheelJoint = 3;
  69993. PhysicsJoint.SliderJoint = 4;
  69994. //OIMO
  69995. PhysicsJoint.PrismaticJoint = 5;
  69996. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  69997. PhysicsJoint.UniversalJoint = 6;
  69998. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  69999. //Cannon
  70000. //Similar to a Ball-Joint. Different in params
  70001. PhysicsJoint.PointToPointJoint = 8;
  70002. //Cannon only at the moment
  70003. PhysicsJoint.SpringJoint = 9;
  70004. PhysicsJoint.LockJoint = 10;
  70005. return PhysicsJoint;
  70006. }());
  70007. BABYLON.PhysicsJoint = PhysicsJoint;
  70008. /**
  70009. * A class representing a physics distance joint.
  70010. */
  70011. var DistanceJoint = /** @class */ (function (_super) {
  70012. __extends(DistanceJoint, _super);
  70013. function DistanceJoint(jointData) {
  70014. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  70015. }
  70016. /**
  70017. * Update the predefined distance.
  70018. */
  70019. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  70020. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  70021. };
  70022. return DistanceJoint;
  70023. }(PhysicsJoint));
  70024. BABYLON.DistanceJoint = DistanceJoint;
  70025. var MotorEnabledJoint = /** @class */ (function (_super) {
  70026. __extends(MotorEnabledJoint, _super);
  70027. function MotorEnabledJoint(type, jointData) {
  70028. return _super.call(this, type, jointData) || this;
  70029. }
  70030. /**
  70031. * Set the motor values.
  70032. * Attention, this function is plugin specific. Engines won't react 100% the same.
  70033. * @param {number} force the force to apply
  70034. * @param {number} maxForce max force for this motor.
  70035. */
  70036. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  70037. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  70038. };
  70039. /**
  70040. * Set the motor's limits.
  70041. * Attention, this function is plugin specific. Engines won't react 100% the same.
  70042. */
  70043. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  70044. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  70045. };
  70046. return MotorEnabledJoint;
  70047. }(PhysicsJoint));
  70048. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  70049. /**
  70050. * This class represents a single hinge physics joint
  70051. */
  70052. var HingeJoint = /** @class */ (function (_super) {
  70053. __extends(HingeJoint, _super);
  70054. function HingeJoint(jointData) {
  70055. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  70056. }
  70057. /**
  70058. * Set the motor values.
  70059. * Attention, this function is plugin specific. Engines won't react 100% the same.
  70060. * @param {number} force the force to apply
  70061. * @param {number} maxForce max force for this motor.
  70062. */
  70063. HingeJoint.prototype.setMotor = function (force, maxForce) {
  70064. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  70065. };
  70066. /**
  70067. * Set the motor's limits.
  70068. * Attention, this function is plugin specific. Engines won't react 100% the same.
  70069. */
  70070. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  70071. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  70072. };
  70073. return HingeJoint;
  70074. }(MotorEnabledJoint));
  70075. BABYLON.HingeJoint = HingeJoint;
  70076. /**
  70077. * This class represents a dual hinge physics joint (same as wheel joint)
  70078. */
  70079. var Hinge2Joint = /** @class */ (function (_super) {
  70080. __extends(Hinge2Joint, _super);
  70081. function Hinge2Joint(jointData) {
  70082. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  70083. }
  70084. /**
  70085. * Set the motor values.
  70086. * Attention, this function is plugin specific. Engines won't react 100% the same.
  70087. * @param {number} force the force to apply
  70088. * @param {number} maxForce max force for this motor.
  70089. * @param {motorIndex} the motor's index, 0 or 1.
  70090. */
  70091. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  70092. if (motorIndex === void 0) { motorIndex = 0; }
  70093. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  70094. };
  70095. /**
  70096. * Set the motor limits.
  70097. * Attention, this function is plugin specific. Engines won't react 100% the same.
  70098. * @param {number} upperLimit the upper limit
  70099. * @param {number} lowerLimit lower limit
  70100. * @param {motorIndex} the motor's index, 0 or 1.
  70101. */
  70102. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  70103. if (motorIndex === void 0) { motorIndex = 0; }
  70104. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  70105. };
  70106. return Hinge2Joint;
  70107. }(MotorEnabledJoint));
  70108. BABYLON.Hinge2Joint = Hinge2Joint;
  70109. })(BABYLON || (BABYLON = {}));
  70110. //# sourceMappingURL=babylon.physicsJoint.js.map
  70111. var BABYLON;
  70112. (function (BABYLON) {
  70113. var PhysicsImpostor = /** @class */ (function () {
  70114. function PhysicsImpostor(object, type, _options, _scene) {
  70115. if (_options === void 0) { _options = { mass: 0 }; }
  70116. var _this = this;
  70117. this.object = object;
  70118. this.type = type;
  70119. this._options = _options;
  70120. this._scene = _scene;
  70121. this._bodyUpdateRequired = false;
  70122. this._onBeforePhysicsStepCallbacks = new Array();
  70123. this._onAfterPhysicsStepCallbacks = new Array();
  70124. this._onPhysicsCollideCallbacks = [];
  70125. this._deltaPosition = BABYLON.Vector3.Zero();
  70126. this._isDisposed = false;
  70127. //temp variables for parent rotation calculations
  70128. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  70129. this._tmpQuat = new BABYLON.Quaternion();
  70130. this._tmpQuat2 = new BABYLON.Quaternion();
  70131. /**
  70132. * this function is executed by the physics engine.
  70133. */
  70134. this.beforeStep = function () {
  70135. if (!_this._physicsEngine) {
  70136. return;
  70137. }
  70138. _this.object.translate(_this._deltaPosition, -1);
  70139. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  70140. _this.object.computeWorldMatrix(false);
  70141. if (_this.object.parent && _this.object.rotationQuaternion) {
  70142. _this.getParentsRotation();
  70143. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  70144. }
  70145. else {
  70146. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  70147. }
  70148. if (!_this._options.disableBidirectionalTransformation) {
  70149. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  70150. }
  70151. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  70152. func(_this);
  70153. });
  70154. };
  70155. /**
  70156. * this function is executed by the physics engine.
  70157. */
  70158. this.afterStep = function () {
  70159. if (!_this._physicsEngine) {
  70160. return;
  70161. }
  70162. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  70163. func(_this);
  70164. });
  70165. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  70166. // object has now its world rotation. needs to be converted to local.
  70167. if (_this.object.parent && _this.object.rotationQuaternion) {
  70168. _this.getParentsRotation();
  70169. _this._tmpQuat.conjugateInPlace();
  70170. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  70171. }
  70172. // take the position set and make it the absolute position of this object.
  70173. _this.object.setAbsolutePosition(_this.object.position);
  70174. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  70175. _this.object.translate(_this._deltaPosition, 1);
  70176. };
  70177. /**
  70178. * Legacy collision detection event support
  70179. */
  70180. this.onCollideEvent = null;
  70181. //event and body object due to cannon's event-based architecture.
  70182. this.onCollide = function (e) {
  70183. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  70184. return;
  70185. }
  70186. if (!_this._physicsEngine) {
  70187. return;
  70188. }
  70189. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  70190. if (otherImpostor) {
  70191. // Legacy collision detection event support
  70192. if (_this.onCollideEvent) {
  70193. _this.onCollideEvent(_this, otherImpostor);
  70194. }
  70195. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  70196. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  70197. }).forEach(function (obj) {
  70198. obj.callback(_this, otherImpostor);
  70199. });
  70200. }
  70201. };
  70202. //sanity check!
  70203. if (!this.object) {
  70204. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  70205. return;
  70206. }
  70207. //legacy support for old syntax.
  70208. if (!this._scene && object.getScene) {
  70209. this._scene = object.getScene();
  70210. }
  70211. if (!this._scene) {
  70212. return;
  70213. }
  70214. this._physicsEngine = this._scene.getPhysicsEngine();
  70215. if (!this._physicsEngine) {
  70216. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  70217. }
  70218. else {
  70219. //set the object's quaternion, if not set
  70220. if (!this.object.rotationQuaternion) {
  70221. if (this.object.rotation) {
  70222. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  70223. }
  70224. else {
  70225. this.object.rotationQuaternion = new BABYLON.Quaternion();
  70226. }
  70227. }
  70228. //default options params
  70229. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  70230. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  70231. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  70232. this._joints = [];
  70233. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  70234. if (!this.object.parent || this._options.ignoreParent) {
  70235. this._init();
  70236. }
  70237. else if (this.object.parent.physicsImpostor) {
  70238. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  70239. }
  70240. }
  70241. }
  70242. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  70243. get: function () {
  70244. return this._isDisposed;
  70245. },
  70246. enumerable: true,
  70247. configurable: true
  70248. });
  70249. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  70250. get: function () {
  70251. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  70252. },
  70253. set: function (value) {
  70254. this.setMass(value);
  70255. },
  70256. enumerable: true,
  70257. configurable: true
  70258. });
  70259. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  70260. get: function () {
  70261. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  70262. },
  70263. set: function (value) {
  70264. if (!this._physicsEngine) {
  70265. return;
  70266. }
  70267. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  70268. },
  70269. enumerable: true,
  70270. configurable: true
  70271. });
  70272. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  70273. get: function () {
  70274. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  70275. },
  70276. set: function (value) {
  70277. if (!this._physicsEngine) {
  70278. return;
  70279. }
  70280. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  70281. },
  70282. enumerable: true,
  70283. configurable: true
  70284. });
  70285. /**
  70286. * This function will completly initialize this impostor.
  70287. * It will create a new body - but only if this mesh has no parent.
  70288. * If it has, this impostor will not be used other than to define the impostor
  70289. * of the child mesh.
  70290. */
  70291. PhysicsImpostor.prototype._init = function () {
  70292. if (!this._physicsEngine) {
  70293. return;
  70294. }
  70295. this._physicsEngine.removeImpostor(this);
  70296. this.physicsBody = null;
  70297. this._parent = this._parent || this._getPhysicsParent();
  70298. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  70299. this._physicsEngine.addImpostor(this);
  70300. }
  70301. };
  70302. PhysicsImpostor.prototype._getPhysicsParent = function () {
  70303. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  70304. var parentMesh = this.object.parent;
  70305. return parentMesh.physicsImpostor;
  70306. }
  70307. return null;
  70308. };
  70309. /**
  70310. * Should a new body be generated.
  70311. */
  70312. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  70313. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  70314. };
  70315. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  70316. this.forceUpdate();
  70317. };
  70318. /**
  70319. * Force a regeneration of this or the parent's impostor's body.
  70320. * Use under cautious - This will remove all joints already implemented.
  70321. */
  70322. PhysicsImpostor.prototype.forceUpdate = function () {
  70323. this._init();
  70324. if (this.parent && !this._options.ignoreParent) {
  70325. this.parent.forceUpdate();
  70326. }
  70327. };
  70328. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  70329. /*public get mesh(): AbstractMesh {
  70330. return this._mesh;
  70331. }*/
  70332. /**
  70333. * Gets the body that holds this impostor. Either its own, or its parent.
  70334. */
  70335. get: function () {
  70336. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  70337. },
  70338. /**
  70339. * Set the physics body. Used mainly by the physics engine/plugin
  70340. */
  70341. set: function (physicsBody) {
  70342. if (this._physicsBody && this._physicsEngine) {
  70343. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  70344. }
  70345. this._physicsBody = physicsBody;
  70346. this.resetUpdateFlags();
  70347. },
  70348. enumerable: true,
  70349. configurable: true
  70350. });
  70351. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  70352. get: function () {
  70353. return !this._options.ignoreParent && this._parent ? this._parent : null;
  70354. },
  70355. set: function (value) {
  70356. this._parent = value;
  70357. },
  70358. enumerable: true,
  70359. configurable: true
  70360. });
  70361. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  70362. this._bodyUpdateRequired = false;
  70363. };
  70364. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  70365. if (this.object.getBoundingInfo) {
  70366. var q = this.object.rotationQuaternion;
  70367. //reset rotation
  70368. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  70369. //calculate the world matrix with no rotation
  70370. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  70371. var boundingInfo = this.object.getBoundingInfo();
  70372. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  70373. //bring back the rotation
  70374. this.object.rotationQuaternion = q;
  70375. //calculate the world matrix with the new rotation
  70376. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  70377. return size;
  70378. }
  70379. else {
  70380. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  70381. }
  70382. };
  70383. PhysicsImpostor.prototype.getObjectCenter = function () {
  70384. if (this.object.getBoundingInfo) {
  70385. var boundingInfo = this.object.getBoundingInfo();
  70386. return boundingInfo.boundingBox.centerWorld;
  70387. }
  70388. else {
  70389. return this.object.position;
  70390. }
  70391. };
  70392. /**
  70393. * Get a specific parametes from the options parameter.
  70394. */
  70395. PhysicsImpostor.prototype.getParam = function (paramName) {
  70396. return this._options[paramName];
  70397. };
  70398. /**
  70399. * Sets a specific parameter in the options given to the physics plugin
  70400. */
  70401. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  70402. this._options[paramName] = value;
  70403. this._bodyUpdateRequired = true;
  70404. };
  70405. /**
  70406. * Specifically change the body's mass option. Won't recreate the physics body object
  70407. */
  70408. PhysicsImpostor.prototype.setMass = function (mass) {
  70409. if (this.getParam("mass") !== mass) {
  70410. this.setParam("mass", mass);
  70411. }
  70412. if (this._physicsEngine) {
  70413. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  70414. }
  70415. };
  70416. PhysicsImpostor.prototype.getLinearVelocity = function () {
  70417. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  70418. };
  70419. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  70420. if (this._physicsEngine) {
  70421. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  70422. }
  70423. };
  70424. PhysicsImpostor.prototype.getAngularVelocity = function () {
  70425. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  70426. };
  70427. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  70428. if (this._physicsEngine) {
  70429. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  70430. }
  70431. };
  70432. /**
  70433. * Execute a function with the physics plugin native code.
  70434. * Provide a function the will have two variables - the world object and the physics body object.
  70435. */
  70436. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  70437. if (this._physicsEngine) {
  70438. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  70439. }
  70440. };
  70441. /**
  70442. * Register a function that will be executed before the physics world is stepping forward.
  70443. */
  70444. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  70445. this._onBeforePhysicsStepCallbacks.push(func);
  70446. };
  70447. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  70448. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  70449. if (index > -1) {
  70450. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  70451. }
  70452. else {
  70453. BABYLON.Tools.Warn("Function to remove was not found");
  70454. }
  70455. };
  70456. /**
  70457. * Register a function that will be executed after the physics step
  70458. */
  70459. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  70460. this._onAfterPhysicsStepCallbacks.push(func);
  70461. };
  70462. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  70463. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  70464. if (index > -1) {
  70465. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  70466. }
  70467. else {
  70468. BABYLON.Tools.Warn("Function to remove was not found");
  70469. }
  70470. };
  70471. /**
  70472. * register a function that will be executed when this impostor collides against a different body.
  70473. */
  70474. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  70475. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  70476. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  70477. };
  70478. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  70479. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  70480. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  70481. if (index > -1) {
  70482. this._onPhysicsCollideCallbacks.splice(index, 1);
  70483. }
  70484. else {
  70485. BABYLON.Tools.Warn("Function to remove was not found");
  70486. }
  70487. };
  70488. PhysicsImpostor.prototype.getParentsRotation = function () {
  70489. var parent = this.object.parent;
  70490. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  70491. while (parent) {
  70492. if (parent.rotationQuaternion) {
  70493. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  70494. }
  70495. else {
  70496. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  70497. }
  70498. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  70499. parent = parent.parent;
  70500. }
  70501. return this._tmpQuat;
  70502. };
  70503. /**
  70504. * Apply a force
  70505. */
  70506. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  70507. if (this._physicsEngine) {
  70508. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  70509. }
  70510. return this;
  70511. };
  70512. /**
  70513. * Apply an impulse
  70514. */
  70515. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  70516. if (this._physicsEngine) {
  70517. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  70518. }
  70519. return this;
  70520. };
  70521. /**
  70522. * A help function to create a joint.
  70523. */
  70524. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  70525. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  70526. this.addJoint(otherImpostor, joint);
  70527. return this;
  70528. };
  70529. /**
  70530. * Add a joint to this impostor with a different impostor.
  70531. */
  70532. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  70533. this._joints.push({
  70534. otherImpostor: otherImpostor,
  70535. joint: joint
  70536. });
  70537. if (this._physicsEngine) {
  70538. this._physicsEngine.addJoint(this, otherImpostor, joint);
  70539. }
  70540. return this;
  70541. };
  70542. /**
  70543. * Will keep this body still, in a sleep mode.
  70544. */
  70545. PhysicsImpostor.prototype.sleep = function () {
  70546. if (this._physicsEngine) {
  70547. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  70548. }
  70549. return this;
  70550. };
  70551. /**
  70552. * Wake the body up.
  70553. */
  70554. PhysicsImpostor.prototype.wakeUp = function () {
  70555. if (this._physicsEngine) {
  70556. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  70557. }
  70558. return this;
  70559. };
  70560. PhysicsImpostor.prototype.clone = function (newObject) {
  70561. if (!newObject)
  70562. return null;
  70563. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  70564. };
  70565. PhysicsImpostor.prototype.dispose = function () {
  70566. var _this = this;
  70567. //no dispose if no physics engine is available.
  70568. if (!this._physicsEngine) {
  70569. return;
  70570. }
  70571. this._joints.forEach(function (j) {
  70572. if (_this._physicsEngine) {
  70573. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  70574. }
  70575. });
  70576. //dispose the physics body
  70577. this._physicsEngine.removeImpostor(this);
  70578. if (this.parent) {
  70579. this.parent.forceUpdate();
  70580. }
  70581. else {
  70582. /*this._object.getChildMeshes().forEach(function(mesh) {
  70583. if (mesh.physicsImpostor) {
  70584. if (disposeChildren) {
  70585. mesh.physicsImpostor.dispose();
  70586. mesh.physicsImpostor = null;
  70587. }
  70588. }
  70589. })*/
  70590. }
  70591. this._isDisposed = true;
  70592. };
  70593. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  70594. this._deltaPosition.copyFrom(position);
  70595. };
  70596. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  70597. if (!this._deltaRotation) {
  70598. this._deltaRotation = new BABYLON.Quaternion();
  70599. }
  70600. this._deltaRotation.copyFrom(rotation);
  70601. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  70602. };
  70603. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  70604. if (this._physicsEngine) {
  70605. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  70606. }
  70607. return this;
  70608. };
  70609. PhysicsImpostor.prototype.getRadius = function () {
  70610. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  70611. };
  70612. /**
  70613. * Sync a bone with this impostor
  70614. * @param bone The bone to sync to the impostor.
  70615. * @param boneMesh The mesh that the bone is influencing.
  70616. * @param jointPivot The pivot of the joint / bone in local space.
  70617. * @param distToJoint Optional distance from the impostor to the joint.
  70618. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  70619. */
  70620. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  70621. var tempVec = PhysicsImpostor._tmpVecs[0];
  70622. var mesh = this.object;
  70623. if (mesh.rotationQuaternion) {
  70624. if (adjustRotation) {
  70625. var tempQuat = PhysicsImpostor._tmpQuat;
  70626. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  70627. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  70628. }
  70629. else {
  70630. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  70631. }
  70632. }
  70633. tempVec.x = 0;
  70634. tempVec.y = 0;
  70635. tempVec.z = 0;
  70636. if (jointPivot) {
  70637. tempVec.x = jointPivot.x;
  70638. tempVec.y = jointPivot.y;
  70639. tempVec.z = jointPivot.z;
  70640. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  70641. if (distToJoint === undefined || distToJoint === null) {
  70642. distToJoint = jointPivot.length();
  70643. }
  70644. tempVec.x *= distToJoint;
  70645. tempVec.y *= distToJoint;
  70646. tempVec.z *= distToJoint;
  70647. }
  70648. if (bone.getParent()) {
  70649. tempVec.addInPlace(mesh.getAbsolutePosition());
  70650. bone.setAbsolutePosition(tempVec, boneMesh);
  70651. }
  70652. else {
  70653. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  70654. boneMesh.position.x -= tempVec.x;
  70655. boneMesh.position.y -= tempVec.y;
  70656. boneMesh.position.z -= tempVec.z;
  70657. }
  70658. };
  70659. /**
  70660. * Sync impostor to a bone
  70661. * @param bone The bone that the impostor will be synced to.
  70662. * @param boneMesh The mesh that the bone is influencing.
  70663. * @param jointPivot The pivot of the joint / bone in local space.
  70664. * @param distToJoint Optional distance from the impostor to the joint.
  70665. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  70666. * @param boneAxis Optional vector3 axis the bone is aligned with
  70667. */
  70668. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  70669. var mesh = this.object;
  70670. if (mesh.rotationQuaternion) {
  70671. if (adjustRotation) {
  70672. var tempQuat = PhysicsImpostor._tmpQuat;
  70673. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  70674. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  70675. }
  70676. else {
  70677. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  70678. }
  70679. }
  70680. var pos = PhysicsImpostor._tmpVecs[0];
  70681. var boneDir = PhysicsImpostor._tmpVecs[1];
  70682. if (!boneAxis) {
  70683. boneAxis = PhysicsImpostor._tmpVecs[2];
  70684. boneAxis.x = 0;
  70685. boneAxis.y = 1;
  70686. boneAxis.z = 0;
  70687. }
  70688. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  70689. bone.getAbsolutePositionToRef(boneMesh, pos);
  70690. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  70691. distToJoint = jointPivot.length();
  70692. }
  70693. if (distToJoint !== undefined && distToJoint !== null) {
  70694. pos.x += boneDir.x * distToJoint;
  70695. pos.y += boneDir.y * distToJoint;
  70696. pos.z += boneDir.z * distToJoint;
  70697. }
  70698. mesh.setAbsolutePosition(pos);
  70699. };
  70700. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  70701. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  70702. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  70703. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  70704. //Impostor types
  70705. PhysicsImpostor.NoImpostor = 0;
  70706. PhysicsImpostor.SphereImpostor = 1;
  70707. PhysicsImpostor.BoxImpostor = 2;
  70708. PhysicsImpostor.PlaneImpostor = 3;
  70709. PhysicsImpostor.MeshImpostor = 4;
  70710. PhysicsImpostor.CylinderImpostor = 7;
  70711. PhysicsImpostor.ParticleImpostor = 8;
  70712. PhysicsImpostor.HeightmapImpostor = 9;
  70713. return PhysicsImpostor;
  70714. }());
  70715. BABYLON.PhysicsImpostor = PhysicsImpostor;
  70716. })(BABYLON || (BABYLON = {}));
  70717. //# sourceMappingURL=babylon.physicsImpostor.js.map
  70718. var BABYLON;
  70719. (function (BABYLON) {
  70720. var PhysicsEngine = /** @class */ (function () {
  70721. function PhysicsEngine(gravity, _physicsPlugin) {
  70722. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  70723. this._physicsPlugin = _physicsPlugin;
  70724. //new methods and parameters
  70725. this._impostors = [];
  70726. this._joints = [];
  70727. if (!this._physicsPlugin.isSupported()) {
  70728. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  70729. + "Please make sure it is included.");
  70730. }
  70731. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  70732. this.setGravity(gravity);
  70733. this.setTimeStep();
  70734. }
  70735. PhysicsEngine.prototype.setGravity = function (gravity) {
  70736. this.gravity = gravity;
  70737. this._physicsPlugin.setGravity(this.gravity);
  70738. };
  70739. /**
  70740. * Set the time step of the physics engine.
  70741. * default is 1/60.
  70742. * To slow it down, enter 1/600 for example.
  70743. * To speed it up, 1/30
  70744. * @param {number} newTimeStep the new timestep to apply to this world.
  70745. */
  70746. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  70747. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  70748. this._physicsPlugin.setTimeStep(newTimeStep);
  70749. };
  70750. /**
  70751. * Get the time step of the physics engine.
  70752. */
  70753. PhysicsEngine.prototype.getTimeStep = function () {
  70754. return this._physicsPlugin.getTimeStep();
  70755. };
  70756. PhysicsEngine.prototype.dispose = function () {
  70757. this._impostors.forEach(function (impostor) {
  70758. impostor.dispose();
  70759. });
  70760. this._physicsPlugin.dispose();
  70761. };
  70762. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  70763. return this._physicsPlugin.name;
  70764. };
  70765. /**
  70766. * Adding a new impostor for the impostor tracking.
  70767. * This will be done by the impostor itself.
  70768. * @param {PhysicsImpostor} impostor the impostor to add
  70769. */
  70770. PhysicsEngine.prototype.addImpostor = function (impostor) {
  70771. impostor.uniqueId = this._impostors.push(impostor);
  70772. //if no parent, generate the body
  70773. if (!impostor.parent) {
  70774. this._physicsPlugin.generatePhysicsBody(impostor);
  70775. }
  70776. };
  70777. /**
  70778. * Remove an impostor from the engine.
  70779. * This impostor and its mesh will not longer be updated by the physics engine.
  70780. * @param {PhysicsImpostor} impostor the impostor to remove
  70781. */
  70782. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  70783. var index = this._impostors.indexOf(impostor);
  70784. if (index > -1) {
  70785. var removed = this._impostors.splice(index, 1);
  70786. //Is it needed?
  70787. if (removed.length) {
  70788. //this will also remove it from the world.
  70789. removed[0].physicsBody = null;
  70790. }
  70791. }
  70792. };
  70793. /**
  70794. * Add a joint to the physics engine
  70795. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  70796. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  70797. * @param {PhysicsJoint} the joint that will connect both impostors.
  70798. */
  70799. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  70800. var impostorJoint = {
  70801. mainImpostor: mainImpostor,
  70802. connectedImpostor: connectedImpostor,
  70803. joint: joint
  70804. };
  70805. joint.physicsPlugin = this._physicsPlugin;
  70806. this._joints.push(impostorJoint);
  70807. this._physicsPlugin.generateJoint(impostorJoint);
  70808. };
  70809. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  70810. var matchingJoints = this._joints.filter(function (impostorJoint) {
  70811. return (impostorJoint.connectedImpostor === connectedImpostor
  70812. && impostorJoint.joint === joint
  70813. && impostorJoint.mainImpostor === mainImpostor);
  70814. });
  70815. if (matchingJoints.length) {
  70816. this._physicsPlugin.removeJoint(matchingJoints[0]);
  70817. //TODO remove it from the list as well
  70818. }
  70819. };
  70820. /**
  70821. * Called by the scene. no need to call it.
  70822. */
  70823. PhysicsEngine.prototype._step = function (delta) {
  70824. var _this = this;
  70825. //check if any mesh has no body / requires an update
  70826. this._impostors.forEach(function (impostor) {
  70827. if (impostor.isBodyInitRequired()) {
  70828. _this._physicsPlugin.generatePhysicsBody(impostor);
  70829. }
  70830. });
  70831. if (delta > 0.1) {
  70832. delta = 0.1;
  70833. }
  70834. else if (delta <= 0) {
  70835. delta = 1.0 / 60.0;
  70836. }
  70837. this._physicsPlugin.executeStep(delta, this._impostors);
  70838. };
  70839. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  70840. return this._physicsPlugin;
  70841. };
  70842. PhysicsEngine.prototype.getImpostors = function () {
  70843. return this._impostors;
  70844. };
  70845. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  70846. for (var i = 0; i < this._impostors.length; ++i) {
  70847. if (this._impostors[i].object === object) {
  70848. return this._impostors[i];
  70849. }
  70850. }
  70851. return null;
  70852. };
  70853. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  70854. for (var i = 0; i < this._impostors.length; ++i) {
  70855. if (this._impostors[i].physicsBody === body) {
  70856. return this._impostors[i];
  70857. }
  70858. }
  70859. return null;
  70860. };
  70861. // Statics
  70862. PhysicsEngine.Epsilon = 0.001;
  70863. return PhysicsEngine;
  70864. }());
  70865. BABYLON.PhysicsEngine = PhysicsEngine;
  70866. })(BABYLON || (BABYLON = {}));
  70867. //# sourceMappingURL=babylon.physicsEngine.js.map
  70868. var BABYLON;
  70869. (function (BABYLON) {
  70870. var PhysicsHelper = /** @class */ (function () {
  70871. function PhysicsHelper(scene) {
  70872. this._scene = scene;
  70873. this._physicsEngine = this._scene.getPhysicsEngine();
  70874. if (!this._physicsEngine) {
  70875. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  70876. }
  70877. }
  70878. /**
  70879. * @param {Vector3} origin the origin of the explosion
  70880. * @param {number} radius the explosion radius
  70881. * @param {number} strength the explosion strength
  70882. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  70883. */
  70884. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  70885. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  70886. if (!this._physicsEngine) {
  70887. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  70888. return null;
  70889. }
  70890. var impostors = this._physicsEngine.getImpostors();
  70891. if (impostors.length === 0) {
  70892. return null;
  70893. }
  70894. var event = new PhysicsRadialExplosionEvent(this._scene);
  70895. impostors.forEach(function (impostor) {
  70896. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  70897. if (!impostorForceAndContactPoint) {
  70898. return;
  70899. }
  70900. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  70901. });
  70902. event.dispose(false);
  70903. return event;
  70904. };
  70905. /**
  70906. * @param {Vector3} origin the origin of the explosion
  70907. * @param {number} radius the explosion radius
  70908. * @param {number} strength the explosion strength
  70909. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  70910. */
  70911. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  70912. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  70913. if (!this._physicsEngine) {
  70914. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  70915. return null;
  70916. }
  70917. var impostors = this._physicsEngine.getImpostors();
  70918. if (impostors.length === 0) {
  70919. return null;
  70920. }
  70921. var event = new PhysicsRadialExplosionEvent(this._scene);
  70922. impostors.forEach(function (impostor) {
  70923. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  70924. if (!impostorForceAndContactPoint) {
  70925. return;
  70926. }
  70927. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  70928. });
  70929. event.dispose(false);
  70930. return event;
  70931. };
  70932. /**
  70933. * @param {Vector3} origin the origin of the explosion
  70934. * @param {number} radius the explosion radius
  70935. * @param {number} strength the explosion strength
  70936. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  70937. */
  70938. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  70939. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  70940. if (!this._physicsEngine) {
  70941. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  70942. return null;
  70943. }
  70944. var impostors = this._physicsEngine.getImpostors();
  70945. if (impostors.length === 0) {
  70946. return null;
  70947. }
  70948. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  70949. event.dispose(false);
  70950. return event;
  70951. };
  70952. /**
  70953. * @param {Vector3} origin the origin of the updraft
  70954. * @param {number} radius the radius of the updraft
  70955. * @param {number} strength the strength of the updraft
  70956. * @param {number} height the height of the updraft
  70957. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  70958. */
  70959. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  70960. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  70961. if (!this._physicsEngine) {
  70962. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  70963. return null;
  70964. }
  70965. if (this._physicsEngine.getImpostors().length === 0) {
  70966. return null;
  70967. }
  70968. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  70969. event.dispose(false);
  70970. return event;
  70971. };
  70972. /**
  70973. * @param {Vector3} origin the of the vortex
  70974. * @param {number} radius the radius of the vortex
  70975. * @param {number} strength the strength of the vortex
  70976. * @param {number} height the height of the vortex
  70977. */
  70978. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  70979. if (!this._physicsEngine) {
  70980. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  70981. return null;
  70982. }
  70983. if (this._physicsEngine.getImpostors().length === 0) {
  70984. return null;
  70985. }
  70986. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  70987. event.dispose(false);
  70988. return event;
  70989. };
  70990. return PhysicsHelper;
  70991. }());
  70992. BABYLON.PhysicsHelper = PhysicsHelper;
  70993. /***** Radial explosion *****/
  70994. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  70995. function PhysicsRadialExplosionEvent(scene) {
  70996. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  70997. this._rays = [];
  70998. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  70999. this._scene = scene;
  71000. }
  71001. /**
  71002. * Returns the data related to the radial explosion event (sphere & rays).
  71003. * @returns {PhysicsRadialExplosionEventData}
  71004. */
  71005. PhysicsRadialExplosionEvent.prototype.getData = function () {
  71006. this._dataFetched = true;
  71007. return {
  71008. sphere: this._sphere,
  71009. rays: this._rays,
  71010. };
  71011. };
  71012. /**
  71013. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  71014. * @param impostor
  71015. * @param {Vector3} origin the origin of the explosion
  71016. * @param {number} radius the explosion radius
  71017. * @param {number} strength the explosion strength
  71018. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  71019. * @returns {Nullable<PhysicsForceAndContactPoint>}
  71020. */
  71021. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  71022. if (impostor.mass === 0) {
  71023. return null;
  71024. }
  71025. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  71026. return null;
  71027. }
  71028. if (impostor.object.getClassName() !== 'Mesh') {
  71029. return null;
  71030. }
  71031. var impostorObject = impostor.object;
  71032. var impostorObjectCenter = impostor.getObjectCenter();
  71033. var direction = impostorObjectCenter.subtract(origin);
  71034. var ray = new BABYLON.Ray(origin, direction, radius);
  71035. this._rays.push(ray);
  71036. var hit = ray.intersectsMesh(impostorObject);
  71037. var contactPoint = hit.pickedPoint;
  71038. if (!contactPoint) {
  71039. return null;
  71040. }
  71041. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  71042. if (distanceFromOrigin > radius) {
  71043. return null;
  71044. }
  71045. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  71046. ? strength
  71047. : strength * (1 - (distanceFromOrigin / radius));
  71048. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  71049. return { force: force, contactPoint: contactPoint };
  71050. };
  71051. /**
  71052. * Disposes the sphere.
  71053. * @param {bolean} force
  71054. */
  71055. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  71056. var _this = this;
  71057. if (force === void 0) { force = true; }
  71058. if (force) {
  71059. this._sphere.dispose();
  71060. }
  71061. else {
  71062. setTimeout(function () {
  71063. if (!_this._dataFetched) {
  71064. _this._sphere.dispose();
  71065. }
  71066. }, 0);
  71067. }
  71068. };
  71069. /*** Helpers ***/
  71070. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  71071. if (!this._sphere) {
  71072. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  71073. this._sphere.isVisible = false;
  71074. }
  71075. };
  71076. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  71077. var impostorObject = impostor.object;
  71078. this._prepareSphere();
  71079. this._sphere.position = origin;
  71080. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  71081. this._sphere._updateBoundingInfo();
  71082. this._sphere.computeWorldMatrix(true);
  71083. return this._sphere.intersectsMesh(impostorObject, true);
  71084. };
  71085. return PhysicsRadialExplosionEvent;
  71086. }());
  71087. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  71088. /***** Gravitational Field *****/
  71089. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  71090. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  71091. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  71092. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  71093. this._physicsHelper = physicsHelper;
  71094. this._scene = scene;
  71095. this._origin = origin;
  71096. this._radius = radius;
  71097. this._strength = strength;
  71098. this._falloff = falloff;
  71099. this._tickCallback = this._tick.bind(this);
  71100. }
  71101. /**
  71102. * Returns the data related to the gravitational field event (sphere).
  71103. * @returns {PhysicsGravitationalFieldEventData}
  71104. */
  71105. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  71106. this._dataFetched = true;
  71107. return {
  71108. sphere: this._sphere,
  71109. };
  71110. };
  71111. /**
  71112. * Enables the gravitational field.
  71113. */
  71114. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  71115. this._tickCallback.call(this);
  71116. this._scene.registerBeforeRender(this._tickCallback);
  71117. };
  71118. /**
  71119. * Disables the gravitational field.
  71120. */
  71121. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  71122. this._scene.unregisterBeforeRender(this._tickCallback);
  71123. };
  71124. /**
  71125. * Disposes the sphere.
  71126. * @param {bolean} force
  71127. */
  71128. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  71129. var _this = this;
  71130. if (force === void 0) { force = true; }
  71131. if (force) {
  71132. this._sphere.dispose();
  71133. }
  71134. else {
  71135. setTimeout(function () {
  71136. if (!_this._dataFetched) {
  71137. _this._sphere.dispose();
  71138. }
  71139. }, 0);
  71140. }
  71141. };
  71142. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  71143. // Since the params won't change, we fetch the event only once
  71144. if (this._sphere) {
  71145. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  71146. }
  71147. else {
  71148. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  71149. if (radialExplosionEvent) {
  71150. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  71151. }
  71152. }
  71153. };
  71154. return PhysicsGravitationalFieldEvent;
  71155. }());
  71156. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  71157. /***** Updraft *****/
  71158. var PhysicsUpdraftEvent = /** @class */ (function () {
  71159. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  71160. this._scene = _scene;
  71161. this._origin = _origin;
  71162. this._radius = _radius;
  71163. this._strength = _strength;
  71164. this._height = _height;
  71165. this._updraftMode = _updraftMode;
  71166. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  71167. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  71168. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  71169. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  71170. this._physicsEngine = this._scene.getPhysicsEngine();
  71171. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  71172. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  71173. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  71174. this._originDirection = this._origin.subtract(this._originTop).normalize();
  71175. }
  71176. this._tickCallback = this._tick.bind(this);
  71177. }
  71178. /**
  71179. * Returns the data related to the updraft event (cylinder).
  71180. * @returns {PhysicsUpdraftEventData}
  71181. */
  71182. PhysicsUpdraftEvent.prototype.getData = function () {
  71183. this._dataFetched = true;
  71184. return {
  71185. cylinder: this._cylinder,
  71186. };
  71187. };
  71188. /**
  71189. * Enables the updraft.
  71190. */
  71191. PhysicsUpdraftEvent.prototype.enable = function () {
  71192. this._tickCallback.call(this);
  71193. this._scene.registerBeforeRender(this._tickCallback);
  71194. };
  71195. /**
  71196. * Disables the cortex.
  71197. */
  71198. PhysicsUpdraftEvent.prototype.disable = function () {
  71199. this._scene.unregisterBeforeRender(this._tickCallback);
  71200. };
  71201. /**
  71202. * Disposes the sphere.
  71203. * @param {bolean} force
  71204. */
  71205. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  71206. var _this = this;
  71207. if (force === void 0) { force = true; }
  71208. if (force) {
  71209. this._cylinder.dispose();
  71210. }
  71211. else {
  71212. setTimeout(function () {
  71213. if (!_this._dataFetched) {
  71214. _this._cylinder.dispose();
  71215. }
  71216. }, 0);
  71217. }
  71218. };
  71219. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  71220. if (impostor.mass === 0) {
  71221. return null;
  71222. }
  71223. if (!this._intersectsWithCylinder(impostor)) {
  71224. return null;
  71225. }
  71226. var impostorObjectCenter = impostor.getObjectCenter();
  71227. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  71228. var direction = this._originDirection;
  71229. }
  71230. else {
  71231. var direction = impostorObjectCenter.subtract(this._originTop);
  71232. }
  71233. var multiplier = this._strength * -1;
  71234. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  71235. return { force: force, contactPoint: impostorObjectCenter };
  71236. };
  71237. PhysicsUpdraftEvent.prototype._tick = function () {
  71238. var _this = this;
  71239. this._physicsEngine.getImpostors().forEach(function (impostor) {
  71240. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  71241. if (!impostorForceAndContactPoint) {
  71242. return;
  71243. }
  71244. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  71245. });
  71246. };
  71247. /*** Helpers ***/
  71248. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  71249. if (!this._cylinder) {
  71250. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  71251. height: this._height,
  71252. diameter: this._radius * 2,
  71253. }, this._scene);
  71254. this._cylinder.isVisible = false;
  71255. }
  71256. };
  71257. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  71258. var impostorObject = impostor.object;
  71259. this._prepareCylinder();
  71260. this._cylinder.position = this._cylinderPosition;
  71261. return this._cylinder.intersectsMesh(impostorObject, true);
  71262. };
  71263. return PhysicsUpdraftEvent;
  71264. }());
  71265. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  71266. /***** Vortex *****/
  71267. var PhysicsVortexEvent = /** @class */ (function () {
  71268. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  71269. this._scene = _scene;
  71270. this._origin = _origin;
  71271. this._radius = _radius;
  71272. this._strength = _strength;
  71273. this._height = _height;
  71274. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  71275. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  71276. this._updraftMultiplier = 0.02;
  71277. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  71278. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  71279. this._physicsEngine = this._scene.getPhysicsEngine();
  71280. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  71281. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  71282. this._tickCallback = this._tick.bind(this);
  71283. }
  71284. /**
  71285. * Returns the data related to the vortex event (cylinder).
  71286. * @returns {PhysicsVortexEventData}
  71287. */
  71288. PhysicsVortexEvent.prototype.getData = function () {
  71289. this._dataFetched = true;
  71290. return {
  71291. cylinder: this._cylinder,
  71292. };
  71293. };
  71294. /**
  71295. * Enables the vortex.
  71296. */
  71297. PhysicsVortexEvent.prototype.enable = function () {
  71298. this._tickCallback.call(this);
  71299. this._scene.registerBeforeRender(this._tickCallback);
  71300. };
  71301. /**
  71302. * Disables the cortex.
  71303. */
  71304. PhysicsVortexEvent.prototype.disable = function () {
  71305. this._scene.unregisterBeforeRender(this._tickCallback);
  71306. };
  71307. /**
  71308. * Disposes the sphere.
  71309. * @param {bolean} force
  71310. */
  71311. PhysicsVortexEvent.prototype.dispose = function (force) {
  71312. var _this = this;
  71313. if (force === void 0) { force = true; }
  71314. if (force) {
  71315. this._cylinder.dispose();
  71316. }
  71317. else {
  71318. setTimeout(function () {
  71319. if (!_this._dataFetched) {
  71320. _this._cylinder.dispose();
  71321. }
  71322. }, 0);
  71323. }
  71324. };
  71325. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  71326. if (impostor.mass === 0) {
  71327. return null;
  71328. }
  71329. if (!this._intersectsWithCylinder(impostor)) {
  71330. return null;
  71331. }
  71332. if (impostor.object.getClassName() !== 'Mesh') {
  71333. return null;
  71334. }
  71335. var impostorObject = impostor.object;
  71336. var impostorObjectCenter = impostor.getObjectCenter();
  71337. var originOnPlane = new BABYLON.Vector3(this._origin.x, impostorObjectCenter.y, this._origin.z); // the distance to the origin as if both objects were on a plane (Y-axis)
  71338. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  71339. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  71340. var hit = ray.intersectsMesh(impostorObject);
  71341. var contactPoint = hit.pickedPoint;
  71342. if (!contactPoint) {
  71343. return null;
  71344. }
  71345. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  71346. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  71347. var directionToOrigin = contactPoint.normalize();
  71348. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  71349. directionToOrigin = directionToOrigin.negate();
  71350. }
  71351. // TODO: find a more physically based solution
  71352. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  71353. var forceX = directionToOrigin.x * this._strength / 8;
  71354. var forceY = directionToOrigin.y * this._updraftMultiplier;
  71355. var forceZ = directionToOrigin.z * this._strength / 8;
  71356. }
  71357. else {
  71358. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  71359. var forceY = this._originTop.y * this._updraftMultiplier;
  71360. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  71361. }
  71362. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  71363. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  71364. return { force: force, contactPoint: impostorObjectCenter };
  71365. };
  71366. PhysicsVortexEvent.prototype._tick = function () {
  71367. var _this = this;
  71368. this._physicsEngine.getImpostors().forEach(function (impostor) {
  71369. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  71370. if (!impostorForceAndContactPoint) {
  71371. return;
  71372. }
  71373. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  71374. });
  71375. };
  71376. /*** Helpers ***/
  71377. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  71378. if (!this._cylinder) {
  71379. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  71380. height: this._height,
  71381. diameter: this._radius * 2,
  71382. }, this._scene);
  71383. this._cylinder.isVisible = false;
  71384. }
  71385. };
  71386. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  71387. var impostorObject = impostor.object;
  71388. this._prepareCylinder();
  71389. this._cylinder.position = this._cylinderPosition;
  71390. return this._cylinder.intersectsMesh(impostorObject, true);
  71391. };
  71392. return PhysicsVortexEvent;
  71393. }());
  71394. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  71395. /***** Enums *****/
  71396. /**
  71397. * The strenght of the force in correspondence to the distance of the affected object
  71398. */
  71399. var PhysicsRadialImpulseFalloff;
  71400. (function (PhysicsRadialImpulseFalloff) {
  71401. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  71402. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  71403. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  71404. /**
  71405. * The strenght of the force in correspondence to the distance of the affected object
  71406. */
  71407. var PhysicsUpdraftMode;
  71408. (function (PhysicsUpdraftMode) {
  71409. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  71410. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  71411. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  71412. })(BABYLON || (BABYLON = {}));
  71413. //# sourceMappingURL=babylon.physicsHelper.js.map
  71414. var BABYLON;
  71415. (function (BABYLON) {
  71416. var CannonJSPlugin = /** @class */ (function () {
  71417. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  71418. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  71419. if (iterations === void 0) { iterations = 10; }
  71420. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  71421. this.name = "CannonJSPlugin";
  71422. this._physicsMaterials = new Array();
  71423. this._fixedTimeStep = 1 / 60;
  71424. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  71425. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  71426. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  71427. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  71428. this._tmpPosition = BABYLON.Vector3.Zero();
  71429. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  71430. this._tmpUnityRotation = new BABYLON.Quaternion();
  71431. if (!this.isSupported()) {
  71432. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  71433. return;
  71434. }
  71435. this._extendNamespace();
  71436. this.world = new this.BJSCANNON.World();
  71437. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  71438. this.world.solver.iterations = iterations;
  71439. }
  71440. CannonJSPlugin.prototype.setGravity = function (gravity) {
  71441. this.world.gravity.copy(gravity);
  71442. };
  71443. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  71444. this._fixedTimeStep = timeStep;
  71445. };
  71446. CannonJSPlugin.prototype.getTimeStep = function () {
  71447. return this._fixedTimeStep;
  71448. };
  71449. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  71450. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  71451. };
  71452. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  71453. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  71454. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  71455. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  71456. };
  71457. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  71458. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  71459. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  71460. impostor.physicsBody.applyForce(impulse, worldPoint);
  71461. };
  71462. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  71463. //parent-child relationship. Does this impostor has a parent impostor?
  71464. if (impostor.parent) {
  71465. if (impostor.physicsBody) {
  71466. this.removePhysicsBody(impostor);
  71467. //TODO is that needed?
  71468. impostor.forceUpdate();
  71469. }
  71470. return;
  71471. }
  71472. //should a new body be created for this impostor?
  71473. if (impostor.isBodyInitRequired()) {
  71474. var shape = this._createShape(impostor);
  71475. //unregister events, if body is being changed
  71476. var oldBody = impostor.physicsBody;
  71477. if (oldBody) {
  71478. this.removePhysicsBody(impostor);
  71479. }
  71480. //create the body and material
  71481. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  71482. var bodyCreationObject = {
  71483. mass: impostor.getParam("mass"),
  71484. material: material
  71485. };
  71486. // A simple extend, in case native options were used.
  71487. var nativeOptions = impostor.getParam("nativeOptions");
  71488. for (var key in nativeOptions) {
  71489. if (nativeOptions.hasOwnProperty(key)) {
  71490. bodyCreationObject[key] = nativeOptions[key];
  71491. }
  71492. }
  71493. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  71494. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  71495. this.world.addEventListener("preStep", impostor.beforeStep);
  71496. this.world.addEventListener("postStep", impostor.afterStep);
  71497. impostor.physicsBody.addShape(shape);
  71498. this.world.add(impostor.physicsBody);
  71499. //try to keep the body moving in the right direction by taking old properties.
  71500. //Should be tested!
  71501. if (oldBody) {
  71502. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  71503. impostor.physicsBody[param].copy(oldBody[param]);
  71504. });
  71505. }
  71506. this._processChildMeshes(impostor);
  71507. }
  71508. //now update the body's transformation
  71509. this._updatePhysicsBodyTransformation(impostor);
  71510. };
  71511. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  71512. var _this = this;
  71513. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  71514. var currentRotation = mainImpostor.object.rotationQuaternion;
  71515. if (meshChildren.length) {
  71516. var processMesh = function (localPosition, mesh) {
  71517. if (!currentRotation || !mesh.rotationQuaternion) {
  71518. return;
  71519. }
  71520. var childImpostor = mesh.getPhysicsImpostor();
  71521. if (childImpostor) {
  71522. var parent = childImpostor.parent;
  71523. if (parent !== mainImpostor) {
  71524. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  71525. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  71526. if (childImpostor.physicsBody) {
  71527. _this.removePhysicsBody(childImpostor);
  71528. childImpostor.physicsBody = null;
  71529. }
  71530. childImpostor.parent = mainImpostor;
  71531. childImpostor.resetUpdateFlags();
  71532. 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));
  71533. //Add the mass of the children.
  71534. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  71535. }
  71536. }
  71537. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  71538. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  71539. };
  71540. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  71541. }
  71542. };
  71543. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  71544. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  71545. this.world.removeEventListener("preStep", impostor.beforeStep);
  71546. this.world.removeEventListener("postStep", impostor.afterStep);
  71547. this.world.remove(impostor.physicsBody);
  71548. };
  71549. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  71550. var mainBody = impostorJoint.mainImpostor.physicsBody;
  71551. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  71552. if (!mainBody || !connectedBody) {
  71553. return;
  71554. }
  71555. var constraint;
  71556. var jointData = impostorJoint.joint.jointData;
  71557. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  71558. var constraintData = {
  71559. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  71560. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  71561. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  71562. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  71563. maxForce: jointData.nativeParams.maxForce,
  71564. collideConnected: !!jointData.collision
  71565. };
  71566. switch (impostorJoint.joint.type) {
  71567. case BABYLON.PhysicsJoint.HingeJoint:
  71568. case BABYLON.PhysicsJoint.Hinge2Joint:
  71569. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  71570. break;
  71571. case BABYLON.PhysicsJoint.DistanceJoint:
  71572. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  71573. break;
  71574. case BABYLON.PhysicsJoint.SpringJoint:
  71575. var springData = jointData;
  71576. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  71577. restLength: springData.length,
  71578. stiffness: springData.stiffness,
  71579. damping: springData.damping,
  71580. localAnchorA: constraintData.pivotA,
  71581. localAnchorB: constraintData.pivotB
  71582. });
  71583. break;
  71584. case BABYLON.PhysicsJoint.LockJoint:
  71585. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  71586. break;
  71587. case BABYLON.PhysicsJoint.PointToPointJoint:
  71588. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  71589. default:
  71590. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  71591. break;
  71592. }
  71593. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  71594. constraint.collideConnected = !!jointData.collision;
  71595. impostorJoint.joint.physicsJoint = constraint;
  71596. //don't add spring as constraint, as it is not one.
  71597. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  71598. this.world.addConstraint(constraint);
  71599. }
  71600. else {
  71601. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  71602. constraint.applyForce();
  71603. });
  71604. }
  71605. };
  71606. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  71607. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  71608. };
  71609. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  71610. var index;
  71611. var mat;
  71612. for (index = 0; index < this._physicsMaterials.length; index++) {
  71613. mat = this._physicsMaterials[index];
  71614. if (mat.friction === friction && mat.restitution === restitution) {
  71615. return mat;
  71616. }
  71617. }
  71618. var currentMat = new this.BJSCANNON.Material(name);
  71619. currentMat.friction = friction;
  71620. currentMat.restitution = restitution;
  71621. this._physicsMaterials.push(currentMat);
  71622. return currentMat;
  71623. };
  71624. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  71625. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  71626. };
  71627. CannonJSPlugin.prototype._createShape = function (impostor) {
  71628. var object = impostor.object;
  71629. var returnValue;
  71630. var extendSize = impostor.getObjectExtendSize();
  71631. switch (impostor.type) {
  71632. case BABYLON.PhysicsImpostor.SphereImpostor:
  71633. var radiusX = extendSize.x;
  71634. var radiusY = extendSize.y;
  71635. var radiusZ = extendSize.z;
  71636. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  71637. break;
  71638. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  71639. case BABYLON.PhysicsImpostor.CylinderImpostor:
  71640. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  71641. break;
  71642. case BABYLON.PhysicsImpostor.BoxImpostor:
  71643. var box = extendSize.scale(0.5);
  71644. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  71645. break;
  71646. case BABYLON.PhysicsImpostor.PlaneImpostor:
  71647. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  71648. returnValue = new this.BJSCANNON.Plane();
  71649. break;
  71650. case BABYLON.PhysicsImpostor.MeshImpostor:
  71651. // should transform the vertex data to world coordinates!!
  71652. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  71653. var rawFaces = object.getIndices ? object.getIndices() : [];
  71654. if (!rawVerts)
  71655. return;
  71656. // get only scale! so the object could transform correctly.
  71657. var oldPosition = object.position.clone();
  71658. var oldRotation = object.rotation && object.rotation.clone();
  71659. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  71660. object.position.copyFromFloats(0, 0, 0);
  71661. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  71662. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  71663. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  71664. var transform = object.computeWorldMatrix(true);
  71665. // convert rawVerts to object space
  71666. var temp = new Array();
  71667. var index;
  71668. for (index = 0; index < rawVerts.length; index += 3) {
  71669. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  71670. }
  71671. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  71672. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  71673. //now set back the transformation!
  71674. object.position.copyFrom(oldPosition);
  71675. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  71676. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  71677. break;
  71678. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  71679. var oldPosition2 = object.position.clone();
  71680. var oldRotation2 = object.rotation && object.rotation.clone();
  71681. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  71682. object.position.copyFromFloats(0, 0, 0);
  71683. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  71684. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  71685. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  71686. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  71687. returnValue = this._createHeightmap(object);
  71688. object.position.copyFrom(oldPosition2);
  71689. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  71690. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  71691. object.computeWorldMatrix(true);
  71692. break;
  71693. case BABYLON.PhysicsImpostor.ParticleImpostor:
  71694. returnValue = new this.BJSCANNON.Particle();
  71695. break;
  71696. }
  71697. return returnValue;
  71698. };
  71699. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  71700. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  71701. var transform = object.computeWorldMatrix(true);
  71702. // convert rawVerts to object space
  71703. var temp = new Array();
  71704. var index;
  71705. for (index = 0; index < pos.length; index += 3) {
  71706. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  71707. }
  71708. pos = temp;
  71709. var matrix = new Array();
  71710. //For now pointDepth will not be used and will be automatically calculated.
  71711. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  71712. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  71713. var boundingInfo = object.getBoundingInfo();
  71714. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  71715. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  71716. var elementSize = dim * 2 / arraySize;
  71717. for (var i = 0; i < pos.length; i = i + 3) {
  71718. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  71719. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  71720. var y = -pos[i + 2] + minY;
  71721. if (!matrix[x]) {
  71722. matrix[x] = [];
  71723. }
  71724. if (!matrix[x][z]) {
  71725. matrix[x][z] = y;
  71726. }
  71727. matrix[x][z] = Math.max(y, matrix[x][z]);
  71728. }
  71729. for (var x = 0; x <= arraySize; ++x) {
  71730. if (!matrix[x]) {
  71731. var loc = 1;
  71732. while (!matrix[(x + loc) % arraySize]) {
  71733. loc++;
  71734. }
  71735. matrix[x] = matrix[(x + loc) % arraySize].slice();
  71736. //console.log("missing x", x);
  71737. }
  71738. for (var z = 0; z <= arraySize; ++z) {
  71739. if (!matrix[x][z]) {
  71740. var loc = 1;
  71741. var newValue;
  71742. while (newValue === undefined) {
  71743. newValue = matrix[x][(z + loc++) % arraySize];
  71744. }
  71745. matrix[x][z] = newValue;
  71746. }
  71747. }
  71748. }
  71749. var shape = new this.BJSCANNON.Heightfield(matrix, {
  71750. elementSize: elementSize
  71751. });
  71752. //For future reference, needed for body transformation
  71753. shape.minY = minY;
  71754. return shape;
  71755. };
  71756. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  71757. var object = impostor.object;
  71758. //make sure it is updated...
  71759. object.computeWorldMatrix && object.computeWorldMatrix(true);
  71760. // The delta between the mesh position and the mesh bounding box center
  71761. var bInfo = object.getBoundingInfo();
  71762. if (!bInfo)
  71763. return;
  71764. var center = impostor.getObjectCenter();
  71765. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  71766. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  71767. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  71768. this._tmpPosition.copyFrom(center);
  71769. var quaternion = object.rotationQuaternion;
  71770. if (!quaternion) {
  71771. return;
  71772. }
  71773. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  71774. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  71775. //-90 DEG in X, precalculated
  71776. quaternion = quaternion.multiply(this._minus90X);
  71777. //Invert! (Precalculated, 90 deg in X)
  71778. //No need to clone. this will never change.
  71779. impostor.setDeltaRotation(this._plus90X);
  71780. }
  71781. //If it is a heightfield, if should be centered.
  71782. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  71783. var mesh = object;
  71784. var boundingInfo = mesh.getBoundingInfo();
  71785. //calculate the correct body position:
  71786. var rotationQuaternion = mesh.rotationQuaternion;
  71787. mesh.rotationQuaternion = this._tmpUnityRotation;
  71788. mesh.computeWorldMatrix(true);
  71789. //get original center with no rotation
  71790. var c = center.clone();
  71791. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  71792. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  71793. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  71794. mesh.setPivotMatrix(p);
  71795. mesh.computeWorldMatrix(true);
  71796. //calculate the translation
  71797. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  71798. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  71799. //add it inverted to the delta
  71800. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  71801. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  71802. //rotation is back
  71803. mesh.rotationQuaternion = rotationQuaternion;
  71804. mesh.setPivotMatrix(oldPivot);
  71805. mesh.computeWorldMatrix(true);
  71806. }
  71807. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  71808. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  71809. //this._tmpPosition.copyFrom(object.position);
  71810. }
  71811. impostor.setDeltaPosition(this._tmpDeltaPosition);
  71812. //Now update the impostor object
  71813. impostor.physicsBody.position.copy(this._tmpPosition);
  71814. impostor.physicsBody.quaternion.copy(quaternion);
  71815. };
  71816. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  71817. impostor.object.position.copyFrom(impostor.physicsBody.position);
  71818. if (impostor.object.rotationQuaternion) {
  71819. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  71820. }
  71821. };
  71822. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  71823. impostor.physicsBody.position.copy(newPosition);
  71824. impostor.physicsBody.quaternion.copy(newRotation);
  71825. };
  71826. CannonJSPlugin.prototype.isSupported = function () {
  71827. return this.BJSCANNON !== undefined;
  71828. };
  71829. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  71830. impostor.physicsBody.velocity.copy(velocity);
  71831. };
  71832. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  71833. impostor.physicsBody.angularVelocity.copy(velocity);
  71834. };
  71835. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  71836. var v = impostor.physicsBody.velocity;
  71837. if (!v) {
  71838. return null;
  71839. }
  71840. return new BABYLON.Vector3(v.x, v.y, v.z);
  71841. };
  71842. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  71843. var v = impostor.physicsBody.angularVelocity;
  71844. if (!v) {
  71845. return null;
  71846. }
  71847. return new BABYLON.Vector3(v.x, v.y, v.z);
  71848. };
  71849. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  71850. impostor.physicsBody.mass = mass;
  71851. impostor.physicsBody.updateMassProperties();
  71852. };
  71853. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  71854. return impostor.physicsBody.mass;
  71855. };
  71856. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  71857. return impostor.physicsBody.material.friction;
  71858. };
  71859. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  71860. impostor.physicsBody.material.friction = friction;
  71861. };
  71862. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  71863. return impostor.physicsBody.material.restitution;
  71864. };
  71865. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  71866. impostor.physicsBody.material.restitution = restitution;
  71867. };
  71868. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  71869. impostor.physicsBody.sleep();
  71870. };
  71871. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  71872. impostor.physicsBody.wakeUp();
  71873. };
  71874. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  71875. joint.physicsJoint.distance = maxDistance;
  71876. };
  71877. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  71878. // if (!motorIndex) {
  71879. // joint.physicsJoint.enableMotor();
  71880. // }
  71881. // }
  71882. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  71883. // if (!motorIndex) {
  71884. // joint.physicsJoint.disableMotor();
  71885. // }
  71886. // }
  71887. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  71888. if (!motorIndex) {
  71889. joint.physicsJoint.enableMotor();
  71890. joint.physicsJoint.setMotorSpeed(speed);
  71891. if (maxForce) {
  71892. this.setLimit(joint, maxForce);
  71893. }
  71894. }
  71895. };
  71896. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  71897. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  71898. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  71899. };
  71900. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  71901. var body = impostor.physicsBody;
  71902. mesh.position.x = body.position.x;
  71903. mesh.position.y = body.position.y;
  71904. mesh.position.z = body.position.z;
  71905. if (mesh.rotationQuaternion) {
  71906. mesh.rotationQuaternion.x = body.quaternion.x;
  71907. mesh.rotationQuaternion.y = body.quaternion.y;
  71908. mesh.rotationQuaternion.z = body.quaternion.z;
  71909. mesh.rotationQuaternion.w = body.quaternion.w;
  71910. }
  71911. };
  71912. CannonJSPlugin.prototype.getRadius = function (impostor) {
  71913. var shape = impostor.physicsBody.shapes[0];
  71914. return shape.boundingSphereRadius;
  71915. };
  71916. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  71917. var shape = impostor.physicsBody.shapes[0];
  71918. result.x = shape.halfExtents.x * 2;
  71919. result.y = shape.halfExtents.y * 2;
  71920. result.z = shape.halfExtents.z * 2;
  71921. };
  71922. CannonJSPlugin.prototype.dispose = function () {
  71923. };
  71924. CannonJSPlugin.prototype._extendNamespace = function () {
  71925. //this will force cannon to execute at least one step when using interpolation
  71926. var step_tmp1 = new this.BJSCANNON.Vec3();
  71927. var Engine = this.BJSCANNON;
  71928. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  71929. maxSubSteps = maxSubSteps || 10;
  71930. timeSinceLastCalled = timeSinceLastCalled || 0;
  71931. if (timeSinceLastCalled === 0) {
  71932. this.internalStep(dt);
  71933. this.time += dt;
  71934. }
  71935. else {
  71936. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  71937. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  71938. var t0 = performance.now();
  71939. for (var i = 0; i !== internalSteps; i++) {
  71940. this.internalStep(dt);
  71941. if (performance.now() - t0 > dt * 1000) {
  71942. break;
  71943. }
  71944. }
  71945. this.time += timeSinceLastCalled;
  71946. var h = this.time % dt;
  71947. var h_div_dt = h / dt;
  71948. var interpvelo = step_tmp1;
  71949. var bodies = this.bodies;
  71950. for (var j = 0; j !== bodies.length; j++) {
  71951. var b = bodies[j];
  71952. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  71953. b.position.vsub(b.previousPosition, interpvelo);
  71954. interpvelo.scale(h_div_dt, interpvelo);
  71955. b.position.vadd(interpvelo, b.interpolatedPosition);
  71956. }
  71957. else {
  71958. b.interpolatedPosition.copy(b.position);
  71959. b.interpolatedQuaternion.copy(b.quaternion);
  71960. }
  71961. }
  71962. }
  71963. };
  71964. };
  71965. return CannonJSPlugin;
  71966. }());
  71967. BABYLON.CannonJSPlugin = CannonJSPlugin;
  71968. })(BABYLON || (BABYLON = {}));
  71969. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  71970. var BABYLON;
  71971. (function (BABYLON) {
  71972. var OimoJSPlugin = /** @class */ (function () {
  71973. function OimoJSPlugin(iterations) {
  71974. this.name = "OimoJSPlugin";
  71975. this._tmpImpostorsArray = [];
  71976. this._tmpPositionVector = BABYLON.Vector3.Zero();
  71977. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  71978. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  71979. this.world.worldscale(1);
  71980. this.world.clear();
  71981. //making sure no stats are calculated
  71982. this.world.isNoStat = true;
  71983. }
  71984. OimoJSPlugin.prototype.setGravity = function (gravity) {
  71985. this.world.gravity.copy(gravity);
  71986. };
  71987. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  71988. this.world.timeStep = timeStep;
  71989. };
  71990. OimoJSPlugin.prototype.getTimeStep = function () {
  71991. return this.world.timeStep;
  71992. };
  71993. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  71994. var _this = this;
  71995. impostors.forEach(function (impostor) {
  71996. impostor.beforeStep();
  71997. });
  71998. this.world.step();
  71999. impostors.forEach(function (impostor) {
  72000. impostor.afterStep();
  72001. //update the ordered impostors array
  72002. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  72003. });
  72004. //check for collisions
  72005. var contact = this.world.contacts;
  72006. while (contact !== null) {
  72007. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  72008. contact = contact.next;
  72009. continue;
  72010. }
  72011. //is this body colliding with any other? get the impostor
  72012. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  72013. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  72014. if (!mainImpostor || !collidingImpostor) {
  72015. contact = contact.next;
  72016. continue;
  72017. }
  72018. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  72019. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  72020. contact = contact.next;
  72021. }
  72022. };
  72023. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  72024. var mass = impostor.physicsBody.massInfo.mass;
  72025. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  72026. };
  72027. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  72028. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  72029. this.applyImpulse(impostor, force, contactPoint);
  72030. };
  72031. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  72032. var _this = this;
  72033. //parent-child relationship. Does this impostor has a parent impostor?
  72034. if (impostor.parent) {
  72035. if (impostor.physicsBody) {
  72036. this.removePhysicsBody(impostor);
  72037. //TODO is that needed?
  72038. impostor.forceUpdate();
  72039. }
  72040. return;
  72041. }
  72042. if (impostor.isBodyInitRequired()) {
  72043. var bodyConfig = {
  72044. name: impostor.uniqueId,
  72045. //Oimo must have mass, also for static objects.
  72046. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  72047. size: [],
  72048. type: [],
  72049. pos: [],
  72050. rot: [],
  72051. move: impostor.getParam("mass") !== 0,
  72052. //Supporting older versions of Oimo
  72053. world: this.world
  72054. };
  72055. var impostors = [impostor];
  72056. var addToArray = function (parent) {
  72057. if (!parent.getChildMeshes)
  72058. return;
  72059. parent.getChildMeshes().forEach(function (m) {
  72060. if (m.physicsImpostor) {
  72061. impostors.push(m.physicsImpostor);
  72062. //m.physicsImpostor._init();
  72063. }
  72064. });
  72065. };
  72066. addToArray(impostor.object);
  72067. var checkWithEpsilon_1 = function (value) {
  72068. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  72069. };
  72070. impostors.forEach(function (i) {
  72071. if (!impostor.object.rotationQuaternion) {
  72072. return;
  72073. }
  72074. //get the correct bounding box
  72075. var oldQuaternion = i.object.rotationQuaternion;
  72076. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  72077. x: impostor.object.rotationQuaternion.x,
  72078. y: impostor.object.rotationQuaternion.y,
  72079. z: impostor.object.rotationQuaternion.z,
  72080. s: impostor.object.rotationQuaternion.w
  72081. });
  72082. var extendSize = i.getObjectExtendSize();
  72083. if (i === impostor) {
  72084. var center = impostor.getObjectCenter();
  72085. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  72086. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  72087. //Can also use Array.prototype.push.apply
  72088. bodyConfig.pos.push(center.x);
  72089. bodyConfig.pos.push(center.y);
  72090. bodyConfig.pos.push(center.z);
  72091. //tmp solution
  72092. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  72093. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  72094. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  72095. }
  72096. else {
  72097. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  72098. bodyConfig.pos.push(localPosition.x);
  72099. bodyConfig.pos.push(localPosition.y);
  72100. bodyConfig.pos.push(localPosition.z);
  72101. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  72102. bodyConfig.rot.push(0);
  72103. bodyConfig.rot.push(0);
  72104. bodyConfig.rot.push(0);
  72105. }
  72106. // register mesh
  72107. switch (i.type) {
  72108. case BABYLON.PhysicsImpostor.ParticleImpostor:
  72109. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  72110. case BABYLON.PhysicsImpostor.SphereImpostor:
  72111. var radiusX = extendSize.x;
  72112. var radiusY = extendSize.y;
  72113. var radiusZ = extendSize.z;
  72114. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  72115. bodyConfig.type.push('sphere');
  72116. //due to the way oimo works with compounds, add 3 times
  72117. bodyConfig.size.push(size);
  72118. bodyConfig.size.push(size);
  72119. bodyConfig.size.push(size);
  72120. break;
  72121. case BABYLON.PhysicsImpostor.CylinderImpostor:
  72122. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  72123. var sizeY = checkWithEpsilon_1(extendSize.y);
  72124. bodyConfig.type.push('cylinder');
  72125. bodyConfig.size.push(sizeX);
  72126. bodyConfig.size.push(sizeY);
  72127. //due to the way oimo works with compounds, add one more value.
  72128. bodyConfig.size.push(sizeY);
  72129. break;
  72130. case BABYLON.PhysicsImpostor.PlaneImpostor:
  72131. case BABYLON.PhysicsImpostor.BoxImpostor:
  72132. default:
  72133. var sizeX = checkWithEpsilon_1(extendSize.x);
  72134. var sizeY = checkWithEpsilon_1(extendSize.y);
  72135. var sizeZ = checkWithEpsilon_1(extendSize.z);
  72136. bodyConfig.type.push('box');
  72137. bodyConfig.size.push(sizeX);
  72138. bodyConfig.size.push(sizeY);
  72139. bodyConfig.size.push(sizeZ);
  72140. break;
  72141. }
  72142. //actually not needed, but hey...
  72143. i.object.rotationQuaternion = oldQuaternion;
  72144. });
  72145. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  72146. }
  72147. else {
  72148. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  72149. }
  72150. impostor.setDeltaPosition(this._tmpPositionVector);
  72151. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  72152. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  72153. };
  72154. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  72155. //impostor.physicsBody.dispose();
  72156. //Same as : (older oimo versions)
  72157. this.world.removeRigidBody(impostor.physicsBody);
  72158. };
  72159. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  72160. var mainBody = impostorJoint.mainImpostor.physicsBody;
  72161. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  72162. if (!mainBody || !connectedBody) {
  72163. return;
  72164. }
  72165. var jointData = impostorJoint.joint.jointData;
  72166. var options = jointData.nativeParams || {};
  72167. var type;
  72168. var nativeJointData = {
  72169. body1: mainBody,
  72170. body2: connectedBody,
  72171. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  72172. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  72173. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  72174. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  72175. min: options.min,
  72176. max: options.max,
  72177. collision: options.collision || jointData.collision,
  72178. spring: options.spring,
  72179. //supporting older version of Oimo
  72180. world: this.world
  72181. };
  72182. switch (impostorJoint.joint.type) {
  72183. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  72184. type = "jointBall";
  72185. break;
  72186. case BABYLON.PhysicsJoint.SpringJoint:
  72187. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  72188. var springData = jointData;
  72189. nativeJointData.min = springData.length || nativeJointData.min;
  72190. //Max should also be set, just make sure it is at least min
  72191. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  72192. case BABYLON.PhysicsJoint.DistanceJoint:
  72193. type = "jointDistance";
  72194. nativeJointData.max = jointData.maxDistance;
  72195. break;
  72196. case BABYLON.PhysicsJoint.PrismaticJoint:
  72197. type = "jointPrisme";
  72198. break;
  72199. case BABYLON.PhysicsJoint.SliderJoint:
  72200. type = "jointSlide";
  72201. break;
  72202. case BABYLON.PhysicsJoint.WheelJoint:
  72203. type = "jointWheel";
  72204. break;
  72205. case BABYLON.PhysicsJoint.HingeJoint:
  72206. default:
  72207. type = "jointHinge";
  72208. break;
  72209. }
  72210. nativeJointData.type = type;
  72211. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  72212. };
  72213. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  72214. //Bug in Oimo prevents us from disposing a joint in the playground
  72215. //joint.joint.physicsJoint.dispose();
  72216. //So we will bruteforce it!
  72217. try {
  72218. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  72219. }
  72220. catch (e) {
  72221. BABYLON.Tools.Warn(e);
  72222. }
  72223. };
  72224. OimoJSPlugin.prototype.isSupported = function () {
  72225. return this.BJSOIMO !== undefined;
  72226. };
  72227. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  72228. if (!impostor.physicsBody.sleeping) {
  72229. //TODO check that
  72230. if (impostor.physicsBody.shapes.next) {
  72231. var parentShape = this._getLastShape(impostor.physicsBody);
  72232. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  72233. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  72234. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  72235. }
  72236. else {
  72237. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  72238. }
  72239. if (impostor.object.rotationQuaternion) {
  72240. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  72241. impostor.object.rotationQuaternion.normalize();
  72242. }
  72243. }
  72244. };
  72245. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  72246. var body = impostor.physicsBody;
  72247. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  72248. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  72249. body.syncShapes();
  72250. body.awake();
  72251. };
  72252. OimoJSPlugin.prototype._getLastShape = function (body) {
  72253. var lastShape = body.shapes;
  72254. while (lastShape.next) {
  72255. lastShape = lastShape.next;
  72256. }
  72257. return lastShape;
  72258. };
  72259. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  72260. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  72261. };
  72262. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  72263. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  72264. };
  72265. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  72266. var v = impostor.physicsBody.linearVelocity;
  72267. if (!v) {
  72268. return null;
  72269. }
  72270. return new BABYLON.Vector3(v.x, v.y, v.z);
  72271. };
  72272. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  72273. var v = impostor.physicsBody.angularVelocity;
  72274. if (!v) {
  72275. return null;
  72276. }
  72277. return new BABYLON.Vector3(v.x, v.y, v.z);
  72278. };
  72279. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  72280. var staticBody = mass === 0;
  72281. //this will actually set the body's density and not its mass.
  72282. //But this is how oimo treats the mass variable.
  72283. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  72284. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  72285. };
  72286. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  72287. return impostor.physicsBody.shapes.density;
  72288. };
  72289. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  72290. return impostor.physicsBody.shapes.friction;
  72291. };
  72292. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  72293. impostor.physicsBody.shapes.friction = friction;
  72294. };
  72295. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  72296. return impostor.physicsBody.shapes.restitution;
  72297. };
  72298. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  72299. impostor.physicsBody.shapes.restitution = restitution;
  72300. };
  72301. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  72302. impostor.physicsBody.sleep();
  72303. };
  72304. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  72305. impostor.physicsBody.awake();
  72306. };
  72307. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  72308. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  72309. if (minDistance !== void 0) {
  72310. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  72311. }
  72312. };
  72313. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  72314. //TODO separate rotational and transational motors.
  72315. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  72316. if (motor) {
  72317. motor.setMotor(speed, maxForce);
  72318. }
  72319. };
  72320. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  72321. //TODO separate rotational and transational motors.
  72322. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  72323. if (motor) {
  72324. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  72325. }
  72326. };
  72327. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  72328. var body = impostor.physicsBody;
  72329. mesh.position.x = body.position.x;
  72330. mesh.position.y = body.position.y;
  72331. mesh.position.z = body.position.z;
  72332. if (mesh.rotationQuaternion) {
  72333. mesh.rotationQuaternion.x = body.orientation.x;
  72334. mesh.rotationQuaternion.y = body.orientation.y;
  72335. mesh.rotationQuaternion.z = body.orientation.z;
  72336. mesh.rotationQuaternion.w = body.orientation.s;
  72337. }
  72338. };
  72339. OimoJSPlugin.prototype.getRadius = function (impostor) {
  72340. return impostor.physicsBody.shapes.radius;
  72341. };
  72342. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  72343. var shape = impostor.physicsBody.shapes;
  72344. result.x = shape.halfWidth * 2;
  72345. result.y = shape.halfHeight * 2;
  72346. result.z = shape.halfDepth * 2;
  72347. };
  72348. OimoJSPlugin.prototype.dispose = function () {
  72349. this.world.clear();
  72350. };
  72351. return OimoJSPlugin;
  72352. }());
  72353. BABYLON.OimoJSPlugin = OimoJSPlugin;
  72354. })(BABYLON || (BABYLON = {}));
  72355. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  72356. var BABYLON;
  72357. (function (BABYLON) {
  72358. /*
  72359. * Based on jsTGALoader - Javascript loader for TGA file
  72360. * By Vincent Thibault
  72361. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  72362. */
  72363. var TGATools = /** @class */ (function () {
  72364. function TGATools() {
  72365. }
  72366. TGATools.GetTGAHeader = function (data) {
  72367. var offset = 0;
  72368. var header = {
  72369. id_length: data[offset++],
  72370. colormap_type: data[offset++],
  72371. image_type: data[offset++],
  72372. colormap_index: data[offset++] | data[offset++] << 8,
  72373. colormap_length: data[offset++] | data[offset++] << 8,
  72374. colormap_size: data[offset++],
  72375. origin: [
  72376. data[offset++] | data[offset++] << 8,
  72377. data[offset++] | data[offset++] << 8
  72378. ],
  72379. width: data[offset++] | data[offset++] << 8,
  72380. height: data[offset++] | data[offset++] << 8,
  72381. pixel_size: data[offset++],
  72382. flags: data[offset++]
  72383. };
  72384. return header;
  72385. };
  72386. TGATools.UploadContent = function (gl, data) {
  72387. // Not enough data to contain header ?
  72388. if (data.length < 19) {
  72389. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  72390. return;
  72391. }
  72392. // Read Header
  72393. var offset = 18;
  72394. var header = TGATools.GetTGAHeader(data);
  72395. // Assume it's a valid Targa file.
  72396. if (header.id_length + offset > data.length) {
  72397. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  72398. return;
  72399. }
  72400. // Skip not needed data
  72401. offset += header.id_length;
  72402. var use_rle = false;
  72403. var use_pal = false;
  72404. var use_grey = false;
  72405. // Get some informations.
  72406. switch (header.image_type) {
  72407. case TGATools._TYPE_RLE_INDEXED:
  72408. use_rle = true;
  72409. case TGATools._TYPE_INDEXED:
  72410. use_pal = true;
  72411. break;
  72412. case TGATools._TYPE_RLE_RGB:
  72413. use_rle = true;
  72414. case TGATools._TYPE_RGB:
  72415. // use_rgb = true;
  72416. break;
  72417. case TGATools._TYPE_RLE_GREY:
  72418. use_rle = true;
  72419. case TGATools._TYPE_GREY:
  72420. use_grey = true;
  72421. break;
  72422. }
  72423. var pixel_data;
  72424. // var numAlphaBits = header.flags & 0xf;
  72425. var pixel_size = header.pixel_size >> 3;
  72426. var pixel_total = header.width * header.height * pixel_size;
  72427. // Read palettes
  72428. var palettes;
  72429. if (use_pal) {
  72430. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  72431. }
  72432. // Read LRE
  72433. if (use_rle) {
  72434. pixel_data = new Uint8Array(pixel_total);
  72435. var c, count, i;
  72436. var localOffset = 0;
  72437. var pixels = new Uint8Array(pixel_size);
  72438. while (offset < pixel_total && localOffset < pixel_total) {
  72439. c = data[offset++];
  72440. count = (c & 0x7f) + 1;
  72441. // RLE pixels
  72442. if (c & 0x80) {
  72443. // Bind pixel tmp array
  72444. for (i = 0; i < pixel_size; ++i) {
  72445. pixels[i] = data[offset++];
  72446. }
  72447. // Copy pixel array
  72448. for (i = 0; i < count; ++i) {
  72449. pixel_data.set(pixels, localOffset + i * pixel_size);
  72450. }
  72451. localOffset += pixel_size * count;
  72452. }
  72453. else {
  72454. count *= pixel_size;
  72455. for (i = 0; i < count; ++i) {
  72456. pixel_data[localOffset + i] = data[offset++];
  72457. }
  72458. localOffset += count;
  72459. }
  72460. }
  72461. }
  72462. else {
  72463. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  72464. }
  72465. // Load to texture
  72466. var x_start, y_start, x_step, y_step, y_end, x_end;
  72467. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  72468. default:
  72469. case TGATools._ORIGIN_UL:
  72470. x_start = 0;
  72471. x_step = 1;
  72472. x_end = header.width;
  72473. y_start = 0;
  72474. y_step = 1;
  72475. y_end = header.height;
  72476. break;
  72477. case TGATools._ORIGIN_BL:
  72478. x_start = 0;
  72479. x_step = 1;
  72480. x_end = header.width;
  72481. y_start = header.height - 1;
  72482. y_step = -1;
  72483. y_end = -1;
  72484. break;
  72485. case TGATools._ORIGIN_UR:
  72486. x_start = header.width - 1;
  72487. x_step = -1;
  72488. x_end = -1;
  72489. y_start = 0;
  72490. y_step = 1;
  72491. y_end = header.height;
  72492. break;
  72493. case TGATools._ORIGIN_BR:
  72494. x_start = header.width - 1;
  72495. x_step = -1;
  72496. x_end = -1;
  72497. y_start = header.height - 1;
  72498. y_step = -1;
  72499. y_end = -1;
  72500. break;
  72501. }
  72502. // Load the specify method
  72503. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  72504. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  72505. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  72506. };
  72507. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  72508. var image = pixel_data, colormap = palettes;
  72509. var width = header.width, height = header.height;
  72510. var color, i = 0, x, y;
  72511. var imageData = new Uint8Array(width * height * 4);
  72512. for (y = y_start; y !== y_end; y += y_step) {
  72513. for (x = x_start; x !== x_end; x += x_step, i++) {
  72514. color = image[i];
  72515. imageData[(x + width * y) * 4 + 3] = 255;
  72516. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  72517. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  72518. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  72519. }
  72520. }
  72521. return imageData;
  72522. };
  72523. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  72524. var image = pixel_data;
  72525. var width = header.width, height = header.height;
  72526. var color, i = 0, x, y;
  72527. var imageData = new Uint8Array(width * height * 4);
  72528. for (y = y_start; y !== y_end; y += y_step) {
  72529. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  72530. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  72531. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  72532. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  72533. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  72534. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  72535. }
  72536. }
  72537. return imageData;
  72538. };
  72539. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  72540. var image = pixel_data;
  72541. var width = header.width, height = header.height;
  72542. var i = 0, x, y;
  72543. var imageData = new Uint8Array(width * height * 4);
  72544. for (y = y_start; y !== y_end; y += y_step) {
  72545. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  72546. imageData[(x + width * y) * 4 + 3] = 255;
  72547. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  72548. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  72549. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  72550. }
  72551. }
  72552. return imageData;
  72553. };
  72554. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  72555. var image = pixel_data;
  72556. var width = header.width, height = header.height;
  72557. var i = 0, x, y;
  72558. var imageData = new Uint8Array(width * height * 4);
  72559. for (y = y_start; y !== y_end; y += y_step) {
  72560. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  72561. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  72562. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  72563. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  72564. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  72565. }
  72566. }
  72567. return imageData;
  72568. };
  72569. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  72570. var image = pixel_data;
  72571. var width = header.width, height = header.height;
  72572. var color, i = 0, x, y;
  72573. var imageData = new Uint8Array(width * height * 4);
  72574. for (y = y_start; y !== y_end; y += y_step) {
  72575. for (x = x_start; x !== x_end; x += x_step, i++) {
  72576. color = image[i];
  72577. imageData[(x + width * y) * 4 + 0] = color;
  72578. imageData[(x + width * y) * 4 + 1] = color;
  72579. imageData[(x + width * y) * 4 + 2] = color;
  72580. imageData[(x + width * y) * 4 + 3] = 255;
  72581. }
  72582. }
  72583. return imageData;
  72584. };
  72585. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  72586. var image = pixel_data;
  72587. var width = header.width, height = header.height;
  72588. var i = 0, x, y;
  72589. var imageData = new Uint8Array(width * height * 4);
  72590. for (y = y_start; y !== y_end; y += y_step) {
  72591. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  72592. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  72593. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  72594. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  72595. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  72596. }
  72597. }
  72598. return imageData;
  72599. };
  72600. //private static _TYPE_NO_DATA = 0;
  72601. TGATools._TYPE_INDEXED = 1;
  72602. TGATools._TYPE_RGB = 2;
  72603. TGATools._TYPE_GREY = 3;
  72604. TGATools._TYPE_RLE_INDEXED = 9;
  72605. TGATools._TYPE_RLE_RGB = 10;
  72606. TGATools._TYPE_RLE_GREY = 11;
  72607. TGATools._ORIGIN_MASK = 0x30;
  72608. TGATools._ORIGIN_SHIFT = 0x04;
  72609. TGATools._ORIGIN_BL = 0x00;
  72610. TGATools._ORIGIN_BR = 0x01;
  72611. TGATools._ORIGIN_UL = 0x02;
  72612. TGATools._ORIGIN_UR = 0x03;
  72613. return TGATools;
  72614. }());
  72615. BABYLON.TGATools = TGATools;
  72616. })(BABYLON || (BABYLON = {}));
  72617. //# sourceMappingURL=babylon.tga.js.map
  72618. var BABYLON;
  72619. (function (BABYLON) {
  72620. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  72621. // All values and structures referenced from:
  72622. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  72623. var DDS_MAGIC = 0x20534444;
  72624. var
  72625. //DDSD_CAPS = 0x1,
  72626. //DDSD_HEIGHT = 0x2,
  72627. //DDSD_WIDTH = 0x4,
  72628. //DDSD_PITCH = 0x8,
  72629. //DDSD_PIXELFORMAT = 0x1000,
  72630. DDSD_MIPMAPCOUNT = 0x20000;
  72631. //DDSD_LINEARSIZE = 0x80000,
  72632. //DDSD_DEPTH = 0x800000;
  72633. // var DDSCAPS_COMPLEX = 0x8,
  72634. // DDSCAPS_MIPMAP = 0x400000,
  72635. // DDSCAPS_TEXTURE = 0x1000;
  72636. var DDSCAPS2_CUBEMAP = 0x200;
  72637. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  72638. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  72639. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  72640. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  72641. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  72642. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  72643. // DDSCAPS2_VOLUME = 0x200000;
  72644. var
  72645. //DDPF_ALPHAPIXELS = 0x1,
  72646. //DDPF_ALPHA = 0x2,
  72647. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  72648. //DDPF_YUV = 0x200,
  72649. DDPF_LUMINANCE = 0x20000;
  72650. function FourCCToInt32(value) {
  72651. return value.charCodeAt(0) +
  72652. (value.charCodeAt(1) << 8) +
  72653. (value.charCodeAt(2) << 16) +
  72654. (value.charCodeAt(3) << 24);
  72655. }
  72656. function Int32ToFourCC(value) {
  72657. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  72658. }
  72659. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  72660. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  72661. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  72662. var FOURCC_DX10 = FourCCToInt32("DX10");
  72663. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  72664. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  72665. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  72666. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  72667. var headerLengthInt = 31; // The header length in 32 bit ints
  72668. // Offsets into the header array
  72669. var off_magic = 0;
  72670. var off_size = 1;
  72671. var off_flags = 2;
  72672. var off_height = 3;
  72673. var off_width = 4;
  72674. var off_mipmapCount = 7;
  72675. var off_pfFlags = 20;
  72676. var off_pfFourCC = 21;
  72677. var off_RGBbpp = 22;
  72678. var off_RMask = 23;
  72679. var off_GMask = 24;
  72680. var off_BMask = 25;
  72681. var off_AMask = 26;
  72682. // var off_caps1 = 27;
  72683. var off_caps2 = 28;
  72684. // var off_caps3 = 29;
  72685. // var off_caps4 = 30;
  72686. var off_dxgiFormat = 32;
  72687. ;
  72688. var DDSTools = /** @class */ (function () {
  72689. function DDSTools() {
  72690. }
  72691. DDSTools.GetDDSInfo = function (arrayBuffer) {
  72692. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  72693. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  72694. var mipmapCount = 1;
  72695. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  72696. mipmapCount = Math.max(1, header[off_mipmapCount]);
  72697. }
  72698. var fourCC = header[off_pfFourCC];
  72699. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  72700. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  72701. switch (fourCC) {
  72702. case FOURCC_D3DFMT_R16G16B16A16F:
  72703. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  72704. break;
  72705. case FOURCC_D3DFMT_R32G32B32A32F:
  72706. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  72707. break;
  72708. case FOURCC_DX10:
  72709. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  72710. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  72711. break;
  72712. }
  72713. }
  72714. return {
  72715. width: header[off_width],
  72716. height: header[off_height],
  72717. mipmapCount: mipmapCount,
  72718. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  72719. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  72720. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  72721. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  72722. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  72723. dxgiFormat: dxgiFormat,
  72724. textureType: textureType
  72725. };
  72726. };
  72727. DDSTools._ToHalfFloat = function (value) {
  72728. if (!DDSTools._FloatView) {
  72729. DDSTools._FloatView = new Float32Array(1);
  72730. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  72731. }
  72732. DDSTools._FloatView[0] = value;
  72733. var x = DDSTools._Int32View[0];
  72734. var bits = (x >> 16) & 0x8000; /* Get the sign */
  72735. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  72736. var e = (x >> 23) & 0xff; /* Using int is faster here */
  72737. /* If zero, or denormal, or exponent underflows too much for a denormal
  72738. * half, return signed zero. */
  72739. if (e < 103) {
  72740. return bits;
  72741. }
  72742. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  72743. if (e > 142) {
  72744. bits |= 0x7c00;
  72745. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  72746. * not Inf, so make sure we set one mantissa bit too. */
  72747. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  72748. return bits;
  72749. }
  72750. /* If exponent underflows but not too much, return a denormal */
  72751. if (e < 113) {
  72752. m |= 0x0800;
  72753. /* Extra rounding may overflow and set mantissa to 0 and exponent
  72754. * to 1, which is OK. */
  72755. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  72756. return bits;
  72757. }
  72758. bits |= ((e - 112) << 10) | (m >> 1);
  72759. bits += m & 1;
  72760. return bits;
  72761. };
  72762. DDSTools._FromHalfFloat = function (value) {
  72763. var s = (value & 0x8000) >> 15;
  72764. var e = (value & 0x7C00) >> 10;
  72765. var f = value & 0x03FF;
  72766. if (e === 0) {
  72767. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  72768. }
  72769. else if (e == 0x1F) {
  72770. return f ? NaN : ((s ? -1 : 1) * Infinity);
  72771. }
  72772. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  72773. };
  72774. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  72775. var destArray = new Float32Array(dataLength);
  72776. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  72777. var index = 0;
  72778. for (var y = 0; y < height; y++) {
  72779. for (var x = 0; x < width; x++) {
  72780. var srcPos = (x + y * width) * 4;
  72781. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  72782. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  72783. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  72784. if (DDSTools.StoreLODInAlphaChannel) {
  72785. destArray[index + 3] = lod;
  72786. }
  72787. else {
  72788. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  72789. }
  72790. index += 4;
  72791. }
  72792. }
  72793. return destArray;
  72794. };
  72795. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  72796. if (DDSTools.StoreLODInAlphaChannel) {
  72797. var destArray = new Uint16Array(dataLength);
  72798. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  72799. var index = 0;
  72800. for (var y = 0; y < height; y++) {
  72801. for (var x = 0; x < width; x++) {
  72802. var srcPos = (x + y * width) * 4;
  72803. destArray[index] = srcData[srcPos];
  72804. destArray[index + 1] = srcData[srcPos + 1];
  72805. destArray[index + 2] = srcData[srcPos + 2];
  72806. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  72807. index += 4;
  72808. }
  72809. }
  72810. return destArray;
  72811. }
  72812. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  72813. };
  72814. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  72815. if (DDSTools.StoreLODInAlphaChannel) {
  72816. var destArray = new Float32Array(dataLength);
  72817. var srcData = new Float32Array(arrayBuffer, dataOffset);
  72818. var index = 0;
  72819. for (var y = 0; y < height; y++) {
  72820. for (var x = 0; x < width; x++) {
  72821. var srcPos = (x + y * width) * 4;
  72822. destArray[index] = srcData[srcPos];
  72823. destArray[index + 1] = srcData[srcPos + 1];
  72824. destArray[index + 2] = srcData[srcPos + 2];
  72825. destArray[index + 3] = lod;
  72826. index += 4;
  72827. }
  72828. }
  72829. return destArray;
  72830. }
  72831. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  72832. };
  72833. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  72834. var destArray = new Uint8Array(dataLength);
  72835. var srcData = new Float32Array(arrayBuffer, dataOffset);
  72836. var index = 0;
  72837. for (var y = 0; y < height; y++) {
  72838. for (var x = 0; x < width; x++) {
  72839. var srcPos = (x + y * width) * 4;
  72840. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  72841. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  72842. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  72843. if (DDSTools.StoreLODInAlphaChannel) {
  72844. destArray[index + 3] = lod;
  72845. }
  72846. else {
  72847. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  72848. }
  72849. index += 4;
  72850. }
  72851. }
  72852. return destArray;
  72853. };
  72854. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  72855. var destArray = new Uint8Array(dataLength);
  72856. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  72857. var index = 0;
  72858. for (var y = 0; y < height; y++) {
  72859. for (var x = 0; x < width; x++) {
  72860. var srcPos = (x + y * width) * 4;
  72861. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  72862. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  72863. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  72864. if (DDSTools.StoreLODInAlphaChannel) {
  72865. destArray[index + 3] = lod;
  72866. }
  72867. else {
  72868. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  72869. }
  72870. index += 4;
  72871. }
  72872. }
  72873. return destArray;
  72874. };
  72875. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  72876. var byteArray = new Uint8Array(dataLength);
  72877. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  72878. var index = 0;
  72879. for (var y = 0; y < height; y++) {
  72880. for (var x = 0; x < width; x++) {
  72881. var srcPos = (x + y * width) * 4;
  72882. byteArray[index] = srcData[srcPos + rOffset];
  72883. byteArray[index + 1] = srcData[srcPos + gOffset];
  72884. byteArray[index + 2] = srcData[srcPos + bOffset];
  72885. byteArray[index + 3] = srcData[srcPos + aOffset];
  72886. index += 4;
  72887. }
  72888. }
  72889. return byteArray;
  72890. };
  72891. DDSTools._ExtractLongWordOrder = function (value) {
  72892. if (value === 0 || value === 255 || value === -16777216) {
  72893. return 0;
  72894. }
  72895. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  72896. };
  72897. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  72898. var byteArray = new Uint8Array(dataLength);
  72899. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  72900. var index = 0;
  72901. for (var y = 0; y < height; y++) {
  72902. for (var x = 0; x < width; x++) {
  72903. var srcPos = (x + y * width) * 3;
  72904. byteArray[index] = srcData[srcPos + rOffset];
  72905. byteArray[index + 1] = srcData[srcPos + gOffset];
  72906. byteArray[index + 2] = srcData[srcPos + bOffset];
  72907. index += 3;
  72908. }
  72909. }
  72910. return byteArray;
  72911. };
  72912. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  72913. var byteArray = new Uint8Array(dataLength);
  72914. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  72915. var index = 0;
  72916. for (var y = 0; y < height; y++) {
  72917. for (var x = 0; x < width; x++) {
  72918. var srcPos = (x + y * width);
  72919. byteArray[index] = srcData[srcPos];
  72920. index++;
  72921. }
  72922. }
  72923. return byteArray;
  72924. };
  72925. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  72926. if (lodIndex === void 0) { lodIndex = -1; }
  72927. var ext = engine.getCaps().s3tc;
  72928. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  72929. var fourCC, width, height, dataLength = 0, dataOffset;
  72930. var byteArray, mipmapCount, mip;
  72931. var internalFormat = 0;
  72932. var format = 0;
  72933. var blockBytes = 1;
  72934. if (header[off_magic] !== DDS_MAGIC) {
  72935. BABYLON.Tools.Error("Invalid magic number in DDS header");
  72936. return;
  72937. }
  72938. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  72939. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  72940. return;
  72941. }
  72942. if (info.isCompressed && !ext) {
  72943. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  72944. return;
  72945. }
  72946. var bpp = header[off_RGBbpp];
  72947. dataOffset = header[off_size] + 4;
  72948. var computeFormats = false;
  72949. if (info.isFourCC) {
  72950. fourCC = header[off_pfFourCC];
  72951. switch (fourCC) {
  72952. case FOURCC_DXT1:
  72953. blockBytes = 8;
  72954. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  72955. break;
  72956. case FOURCC_DXT3:
  72957. blockBytes = 16;
  72958. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  72959. break;
  72960. case FOURCC_DXT5:
  72961. blockBytes = 16;
  72962. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  72963. break;
  72964. case FOURCC_D3DFMT_R16G16B16A16F:
  72965. computeFormats = true;
  72966. break;
  72967. case FOURCC_D3DFMT_R32G32B32A32F:
  72968. computeFormats = true;
  72969. break;
  72970. case FOURCC_DX10:
  72971. // There is an additionnal header so dataOffset need to be changed
  72972. dataOffset += 5 * 4; // 5 uints
  72973. var supported = false;
  72974. switch (info.dxgiFormat) {
  72975. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  72976. computeFormats = true;
  72977. supported = true;
  72978. break;
  72979. case DXGI_FORMAT_B8G8R8X8_UNORM:
  72980. info.isRGB = true;
  72981. info.isFourCC = false;
  72982. bpp = 32;
  72983. supported = true;
  72984. break;
  72985. }
  72986. if (supported) {
  72987. break;
  72988. }
  72989. default:
  72990. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  72991. return;
  72992. }
  72993. }
  72994. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  72995. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  72996. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  72997. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  72998. if (computeFormats) {
  72999. format = engine._getWebGLTextureType(info.textureType);
  73000. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  73001. }
  73002. mipmapCount = 1;
  73003. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  73004. mipmapCount = Math.max(1, header[off_mipmapCount]);
  73005. }
  73006. for (var face = 0; face < faces; face++) {
  73007. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  73008. width = header[off_width];
  73009. height = header[off_height];
  73010. for (mip = 0; mip < mipmapCount; ++mip) {
  73011. if (lodIndex === -1 || lodIndex === mip) {
  73012. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  73013. var i = (lodIndex === -1) ? mip : 0;
  73014. if (!info.isCompressed && info.isFourCC) {
  73015. dataLength = width * height * 4;
  73016. var floatArray = null;
  73017. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  73018. if (bpp === 128) {
  73019. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  73020. }
  73021. else if (bpp === 64) {
  73022. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  73023. }
  73024. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  73025. format = engine._getWebGLTextureType(info.textureType);
  73026. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  73027. }
  73028. else {
  73029. if (bpp === 128) {
  73030. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  73031. }
  73032. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  73033. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  73034. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  73035. format = engine._getWebGLTextureType(info.textureType);
  73036. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  73037. }
  73038. else {
  73039. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  73040. }
  73041. }
  73042. if (floatArray) {
  73043. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  73044. }
  73045. }
  73046. else if (info.isRGB) {
  73047. if (bpp === 24) {
  73048. dataLength = width * height * 3;
  73049. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  73050. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  73051. }
  73052. else {
  73053. dataLength = width * height * 4;
  73054. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  73055. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  73056. }
  73057. }
  73058. else if (info.isLuminance) {
  73059. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  73060. var unpaddedRowSize = width;
  73061. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  73062. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  73063. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  73064. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  73065. }
  73066. else {
  73067. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  73068. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  73069. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  73070. }
  73071. }
  73072. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  73073. width *= 0.5;
  73074. height *= 0.5;
  73075. width = Math.max(1.0, width);
  73076. height = Math.max(1.0, height);
  73077. }
  73078. if (currentFace !== undefined) {
  73079. // Loading a single face
  73080. break;
  73081. }
  73082. }
  73083. };
  73084. DDSTools.StoreLODInAlphaChannel = false;
  73085. return DDSTools;
  73086. }());
  73087. BABYLON.DDSTools = DDSTools;
  73088. })(BABYLON || (BABYLON = {}));
  73089. //# sourceMappingURL=babylon.dds.js.map
  73090. var BABYLON;
  73091. (function (BABYLON) {
  73092. /**
  73093. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  73094. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  73095. */
  73096. var KhronosTextureContainer = /** @class */ (function () {
  73097. /**
  73098. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  73099. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  73100. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  73101. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  73102. */
  73103. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  73104. this.arrayBuffer = arrayBuffer;
  73105. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  73106. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  73107. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  73108. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  73109. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  73110. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  73111. BABYLON.Tools.Error("texture missing KTX identifier");
  73112. return;
  73113. }
  73114. // load the reset of the header in native 32 bit int
  73115. var header = new Int32Array(this.arrayBuffer, 12, 13);
  73116. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  73117. var oppositeEndianess = header[0] === 0x01020304;
  73118. // read all the header elements in order they exist in the file, without modification (sans endainness)
  73119. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  73120. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  73121. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  73122. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  73123. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  73124. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  73125. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  73126. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  73127. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  73128. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  73129. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  73130. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  73131. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  73132. if (this.glType !== 0) {
  73133. BABYLON.Tools.Error("only compressed formats currently supported");
  73134. return;
  73135. }
  73136. else {
  73137. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  73138. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  73139. }
  73140. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  73141. BABYLON.Tools.Error("only 2D textures currently supported");
  73142. return;
  73143. }
  73144. if (this.numberOfArrayElements !== 0) {
  73145. BABYLON.Tools.Error("texture arrays not currently supported");
  73146. return;
  73147. }
  73148. if (this.numberOfFaces !== facesExpected) {
  73149. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  73150. return;
  73151. }
  73152. // we now have a completely validated file, so could use existence of loadType as success
  73153. // would need to make this more elaborate & adjust checks above to support more than one load type
  73154. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  73155. }
  73156. // not as fast hardware based, but will probably never need to use
  73157. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  73158. return ((val & 0xFF) << 24)
  73159. | ((val & 0xFF00) << 8)
  73160. | ((val >> 8) & 0xFF00)
  73161. | ((val >> 24) & 0xFF);
  73162. };
  73163. /**
  73164. * It is assumed that the texture has already been created & is currently bound
  73165. */
  73166. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  73167. switch (this.loadType) {
  73168. case KhronosTextureContainer.COMPRESSED_2D:
  73169. this._upload2DCompressedLevels(gl, loadMipmaps);
  73170. break;
  73171. case KhronosTextureContainer.TEX_2D:
  73172. case KhronosTextureContainer.COMPRESSED_3D:
  73173. case KhronosTextureContainer.TEX_3D:
  73174. }
  73175. };
  73176. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  73177. // initialize width & height for level 1
  73178. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  73179. var width = this.pixelWidth;
  73180. var height = this.pixelHeight;
  73181. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  73182. for (var level = 0; level < mipmapCount; level++) {
  73183. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  73184. for (var face = 0; face < this.numberOfFaces; face++) {
  73185. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  73186. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  73187. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  73188. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  73189. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  73190. }
  73191. width = Math.max(1.0, width * 0.5);
  73192. height = Math.max(1.0, height * 0.5);
  73193. }
  73194. };
  73195. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  73196. // load types
  73197. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  73198. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  73199. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  73200. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  73201. return KhronosTextureContainer;
  73202. }());
  73203. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  73204. })(BABYLON || (BABYLON = {}));
  73205. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  73206. var BABYLON;
  73207. (function (BABYLON) {
  73208. var Debug = /** @class */ (function () {
  73209. function Debug() {
  73210. }
  73211. Debug.AxesViewer = /** @class */ (function () {
  73212. function AxesViewer(scene, scaleLines) {
  73213. if (scaleLines === void 0) { scaleLines = 1; }
  73214. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  73215. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  73216. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  73217. this.scaleLines = 1;
  73218. this.scaleLines = scaleLines;
  73219. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  73220. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  73221. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  73222. this._xmesh.renderingGroupId = 2;
  73223. this._ymesh.renderingGroupId = 2;
  73224. this._zmesh.renderingGroupId = 2;
  73225. this._xmesh.material.checkReadyOnlyOnce = true;
  73226. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  73227. this._ymesh.material.checkReadyOnlyOnce = true;
  73228. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  73229. this._zmesh.material.checkReadyOnlyOnce = true;
  73230. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  73231. this.scene = scene;
  73232. }
  73233. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  73234. var scaleLines = this.scaleLines;
  73235. if (this._xmesh) {
  73236. this._xmesh.position.copyFrom(position);
  73237. }
  73238. if (this._ymesh) {
  73239. this._ymesh.position.copyFrom(position);
  73240. }
  73241. if (this._zmesh) {
  73242. this._zmesh.position.copyFrom(position);
  73243. }
  73244. var point2 = this._xline[1];
  73245. point2.x = xaxis.x * scaleLines;
  73246. point2.y = xaxis.y * scaleLines;
  73247. point2.z = xaxis.z * scaleLines;
  73248. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  73249. point2 = this._yline[1];
  73250. point2.x = yaxis.x * scaleLines;
  73251. point2.y = yaxis.y * scaleLines;
  73252. point2.z = yaxis.z * scaleLines;
  73253. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  73254. point2 = this._zline[1];
  73255. point2.x = zaxis.x * scaleLines;
  73256. point2.y = zaxis.y * scaleLines;
  73257. point2.z = zaxis.z * scaleLines;
  73258. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  73259. };
  73260. AxesViewer.prototype.dispose = function () {
  73261. if (this._xmesh) {
  73262. this._xmesh.dispose();
  73263. }
  73264. if (this._ymesh) {
  73265. this._ymesh.dispose();
  73266. }
  73267. if (this._zmesh) {
  73268. this._zmesh.dispose();
  73269. }
  73270. this._xmesh = null;
  73271. this._ymesh = null;
  73272. this._zmesh = null;
  73273. this.scene = null;
  73274. };
  73275. return AxesViewer;
  73276. }());
  73277. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  73278. __extends(BoneAxesViewer, _super);
  73279. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  73280. if (scaleLines === void 0) { scaleLines = 1; }
  73281. var _this = _super.call(this, scene, scaleLines) || this;
  73282. _this.pos = BABYLON.Vector3.Zero();
  73283. _this.xaxis = BABYLON.Vector3.Zero();
  73284. _this.yaxis = BABYLON.Vector3.Zero();
  73285. _this.zaxis = BABYLON.Vector3.Zero();
  73286. _this.mesh = mesh;
  73287. _this.bone = bone;
  73288. return _this;
  73289. }
  73290. BoneAxesViewer.prototype.update = function () {
  73291. if (!this.mesh || !this.bone) {
  73292. return;
  73293. }
  73294. var bone = this.bone;
  73295. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  73296. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  73297. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  73298. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  73299. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  73300. };
  73301. BoneAxesViewer.prototype.dispose = function () {
  73302. if (this.mesh) {
  73303. this.mesh = null;
  73304. this.bone = null;
  73305. _super.prototype.dispose.call(this);
  73306. }
  73307. };
  73308. return BoneAxesViewer;
  73309. }(Debug.AxesViewer));
  73310. Debug.PhysicsViewer = /** @class */ (function () {
  73311. function PhysicsViewer(scene) {
  73312. this._impostors = [];
  73313. this._meshes = [];
  73314. this._numMeshes = 0;
  73315. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  73316. var physicEngine = this._scene.getPhysicsEngine();
  73317. if (physicEngine) {
  73318. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  73319. }
  73320. }
  73321. PhysicsViewer.prototype._updateDebugMeshes = function () {
  73322. var plugin = this._physicsEnginePlugin;
  73323. for (var i = 0; i < this._numMeshes; i++) {
  73324. var impostor = this._impostors[i];
  73325. if (!impostor) {
  73326. continue;
  73327. }
  73328. if (impostor.isDisposed) {
  73329. this.hideImpostor(this._impostors[i--]);
  73330. }
  73331. else {
  73332. var mesh = this._meshes[i];
  73333. if (mesh && plugin) {
  73334. plugin.syncMeshWithImpostor(mesh, impostor);
  73335. }
  73336. }
  73337. }
  73338. };
  73339. PhysicsViewer.prototype.showImpostor = function (impostor) {
  73340. if (!this._scene) {
  73341. return;
  73342. }
  73343. for (var i = 0; i < this._numMeshes; i++) {
  73344. if (this._impostors[i] == impostor) {
  73345. return;
  73346. }
  73347. }
  73348. var debugMesh = this._getDebugMesh(impostor, this._scene);
  73349. if (debugMesh) {
  73350. this._impostors[this._numMeshes] = impostor;
  73351. this._meshes[this._numMeshes] = debugMesh;
  73352. if (this._numMeshes === 0) {
  73353. this._renderFunction = this._updateDebugMeshes.bind(this);
  73354. this._scene.registerBeforeRender(this._renderFunction);
  73355. }
  73356. this._numMeshes++;
  73357. }
  73358. };
  73359. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  73360. if (!impostor || !this._scene) {
  73361. return;
  73362. }
  73363. var removed = false;
  73364. for (var i = 0; i < this._numMeshes; i++) {
  73365. if (this._impostors[i] == impostor) {
  73366. var mesh = this._meshes[i];
  73367. if (!mesh) {
  73368. continue;
  73369. }
  73370. this._scene.removeMesh(mesh);
  73371. mesh.dispose();
  73372. this._numMeshes--;
  73373. if (this._numMeshes > 0) {
  73374. this._meshes[i] = this._meshes[this._numMeshes];
  73375. this._impostors[i] = this._impostors[this._numMeshes];
  73376. this._meshes[this._numMeshes] = null;
  73377. this._impostors[this._numMeshes] = null;
  73378. }
  73379. else {
  73380. this._meshes[0] = null;
  73381. this._impostors[0] = null;
  73382. }
  73383. removed = true;
  73384. break;
  73385. }
  73386. }
  73387. if (removed && this._numMeshes === 0) {
  73388. this._scene.unregisterBeforeRender(this._renderFunction);
  73389. }
  73390. };
  73391. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  73392. if (!this._debugMaterial) {
  73393. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  73394. this._debugMaterial.wireframe = true;
  73395. }
  73396. return this._debugMaterial;
  73397. };
  73398. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  73399. if (!this._debugBoxMesh) {
  73400. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  73401. this._debugBoxMesh.renderingGroupId = 1;
  73402. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  73403. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  73404. scene.removeMesh(this._debugBoxMesh);
  73405. }
  73406. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  73407. };
  73408. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  73409. if (!this._debugSphereMesh) {
  73410. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  73411. this._debugSphereMesh.renderingGroupId = 1;
  73412. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  73413. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  73414. scene.removeMesh(this._debugSphereMesh);
  73415. }
  73416. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  73417. };
  73418. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  73419. var mesh = null;
  73420. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  73421. mesh = this._getDebugBoxMesh(scene);
  73422. impostor.getBoxSizeToRef(mesh.scaling);
  73423. }
  73424. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  73425. mesh = this._getDebugSphereMesh(scene);
  73426. var radius = impostor.getRadius();
  73427. mesh.scaling.x = radius * 2;
  73428. mesh.scaling.y = radius * 2;
  73429. mesh.scaling.z = radius * 2;
  73430. }
  73431. return mesh;
  73432. };
  73433. PhysicsViewer.prototype.dispose = function () {
  73434. for (var i = 0; i < this._numMeshes; i++) {
  73435. this.hideImpostor(this._impostors[i]);
  73436. }
  73437. if (this._debugBoxMesh) {
  73438. this._debugBoxMesh.dispose();
  73439. }
  73440. if (this._debugSphereMesh) {
  73441. this._debugSphereMesh.dispose();
  73442. }
  73443. if (this._debugMaterial) {
  73444. this._debugMaterial.dispose();
  73445. }
  73446. this._impostors.length = 0;
  73447. this._scene = null;
  73448. this._physicsEnginePlugin = null;
  73449. };
  73450. return PhysicsViewer;
  73451. }());
  73452. Debug.SkeletonViewer = /** @class */ (function () {
  73453. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  73454. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  73455. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  73456. this.skeleton = skeleton;
  73457. this.mesh = mesh;
  73458. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  73459. this.renderingGroupId = renderingGroupId;
  73460. this.color = BABYLON.Color3.White();
  73461. this._debugLines = new Array();
  73462. this._isEnabled = false;
  73463. this._scene = scene;
  73464. this.update();
  73465. this._renderFunction = this.update.bind(this);
  73466. }
  73467. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  73468. get: function () {
  73469. return this._isEnabled;
  73470. },
  73471. set: function (value) {
  73472. if (this._isEnabled === value) {
  73473. return;
  73474. }
  73475. this._isEnabled = value;
  73476. if (value) {
  73477. this._scene.registerBeforeRender(this._renderFunction);
  73478. }
  73479. else {
  73480. this._scene.unregisterBeforeRender(this._renderFunction);
  73481. }
  73482. },
  73483. enumerable: true,
  73484. configurable: true
  73485. });
  73486. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  73487. if (x === void 0) { x = 0; }
  73488. if (y === void 0) { y = 0; }
  73489. if (z === void 0) { z = 0; }
  73490. var tmat = BABYLON.Tmp.Matrix[0];
  73491. var parentBone = bone.getParent();
  73492. tmat.copyFrom(bone.getLocalMatrix());
  73493. if (x !== 0 || y !== 0 || z !== 0) {
  73494. var tmat2 = BABYLON.Tmp.Matrix[1];
  73495. BABYLON.Matrix.IdentityToRef(tmat2);
  73496. tmat2.m[12] = x;
  73497. tmat2.m[13] = y;
  73498. tmat2.m[14] = z;
  73499. tmat2.multiplyToRef(tmat, tmat);
  73500. }
  73501. if (parentBone) {
  73502. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  73503. }
  73504. tmat.multiplyToRef(meshMat, tmat);
  73505. position.x = tmat.m[12];
  73506. position.y = tmat.m[13];
  73507. position.z = tmat.m[14];
  73508. };
  73509. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  73510. var len = bones.length;
  73511. var meshPos = this.mesh.position;
  73512. for (var i = 0; i < len; i++) {
  73513. var bone = bones[i];
  73514. var points = this._debugLines[i];
  73515. if (!points) {
  73516. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  73517. this._debugLines[i] = points;
  73518. }
  73519. this._getBonePosition(points[0], bone, meshMat);
  73520. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  73521. points[0].subtractInPlace(meshPos);
  73522. points[1].subtractInPlace(meshPos);
  73523. }
  73524. };
  73525. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  73526. var len = bones.length;
  73527. var boneNum = 0;
  73528. var meshPos = this.mesh.position;
  73529. for (var i = len - 1; i >= 0; i--) {
  73530. var childBone = bones[i];
  73531. var parentBone = childBone.getParent();
  73532. if (!parentBone) {
  73533. continue;
  73534. }
  73535. var points = this._debugLines[boneNum];
  73536. if (!points) {
  73537. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  73538. this._debugLines[boneNum] = points;
  73539. }
  73540. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  73541. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  73542. points[0].subtractInPlace(meshPos);
  73543. points[1].subtractInPlace(meshPos);
  73544. boneNum++;
  73545. }
  73546. };
  73547. SkeletonViewer.prototype.update = function () {
  73548. if (this.autoUpdateBonesMatrices) {
  73549. this.skeleton.computeAbsoluteTransforms();
  73550. }
  73551. if (this.skeleton.bones[0].length === undefined) {
  73552. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  73553. }
  73554. else {
  73555. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  73556. }
  73557. if (!this._debugMesh) {
  73558. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  73559. this._debugMesh.renderingGroupId = this.renderingGroupId;
  73560. }
  73561. else {
  73562. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  73563. }
  73564. this._debugMesh.position.copyFrom(this.mesh.position);
  73565. this._debugMesh.color = this.color;
  73566. };
  73567. SkeletonViewer.prototype.dispose = function () {
  73568. if (this._debugMesh) {
  73569. this.isEnabled = false;
  73570. this._debugMesh.dispose();
  73571. this._debugMesh = null;
  73572. }
  73573. };
  73574. return SkeletonViewer;
  73575. }());
  73576. return Debug;
  73577. }());
  73578. BABYLON.Debug = Debug;
  73579. })(BABYLON || (BABYLON = {}));
  73580. //# sourceMappingURL=babylon.debugModules.js.map
  73581. var BABYLON;
  73582. (function (BABYLON) {
  73583. var RayHelper = /** @class */ (function () {
  73584. function RayHelper(ray) {
  73585. this.ray = ray;
  73586. }
  73587. RayHelper.CreateAndShow = function (ray, scene, color) {
  73588. var helper = new RayHelper(ray);
  73589. helper.show(scene, color);
  73590. return helper;
  73591. };
  73592. RayHelper.prototype.show = function (scene, color) {
  73593. if (!this._renderFunction && this.ray) {
  73594. var ray = this.ray;
  73595. this._renderFunction = this._render.bind(this);
  73596. this._scene = scene;
  73597. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  73598. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  73599. if (this._renderFunction) {
  73600. this._scene.registerBeforeRender(this._renderFunction);
  73601. }
  73602. }
  73603. if (color && this._renderLine) {
  73604. this._renderLine.color.copyFrom(color);
  73605. }
  73606. };
  73607. RayHelper.prototype.hide = function () {
  73608. if (this._renderFunction && this._scene) {
  73609. this._scene.unregisterBeforeRender(this._renderFunction);
  73610. this._scene = null;
  73611. this._renderFunction = null;
  73612. if (this._renderLine) {
  73613. this._renderLine.dispose();
  73614. this._renderLine = null;
  73615. }
  73616. this._renderPoints = [];
  73617. }
  73618. };
  73619. RayHelper.prototype._render = function () {
  73620. var ray = this.ray;
  73621. if (!ray) {
  73622. return;
  73623. }
  73624. var point = this._renderPoints[1];
  73625. var len = Math.min(ray.length, 1000000);
  73626. point.copyFrom(ray.direction);
  73627. point.scaleInPlace(len);
  73628. point.addInPlace(ray.origin);
  73629. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  73630. };
  73631. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  73632. this._attachedToMesh = mesh;
  73633. var ray = this.ray;
  73634. if (!ray) {
  73635. return;
  73636. }
  73637. if (!ray.direction) {
  73638. ray.direction = BABYLON.Vector3.Zero();
  73639. }
  73640. if (!ray.origin) {
  73641. ray.origin = BABYLON.Vector3.Zero();
  73642. }
  73643. if (length) {
  73644. ray.length = length;
  73645. }
  73646. if (!meshSpaceOrigin) {
  73647. meshSpaceOrigin = BABYLON.Vector3.Zero();
  73648. }
  73649. if (!meshSpaceDirection) {
  73650. // -1 so that this will work with Mesh.lookAt
  73651. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  73652. }
  73653. if (!this._meshSpaceDirection) {
  73654. this._meshSpaceDirection = meshSpaceDirection.clone();
  73655. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  73656. }
  73657. else {
  73658. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  73659. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  73660. }
  73661. if (!this._updateToMeshFunction) {
  73662. this._updateToMeshFunction = this._updateToMesh.bind(this);
  73663. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  73664. }
  73665. this._updateToMesh();
  73666. };
  73667. RayHelper.prototype.detachFromMesh = function () {
  73668. if (this._attachedToMesh) {
  73669. if (this._updateToMeshFunction) {
  73670. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  73671. }
  73672. this._attachedToMesh = null;
  73673. this._updateToMeshFunction = null;
  73674. }
  73675. };
  73676. RayHelper.prototype._updateToMesh = function () {
  73677. var ray = this.ray;
  73678. if (!this._attachedToMesh || !ray) {
  73679. return;
  73680. }
  73681. if (this._attachedToMesh._isDisposed) {
  73682. this.detachFromMesh();
  73683. return;
  73684. }
  73685. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  73686. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  73687. };
  73688. RayHelper.prototype.dispose = function () {
  73689. this.hide();
  73690. this.detachFromMesh();
  73691. this.ray = null;
  73692. };
  73693. return RayHelper;
  73694. }());
  73695. BABYLON.RayHelper = RayHelper;
  73696. })(BABYLON || (BABYLON = {}));
  73697. //# sourceMappingURL=babylon.rayHelper.js.map
  73698. var BABYLON;
  73699. (function (BABYLON) {
  73700. // load the inspector using require, if not present in the global namespace.
  73701. var DebugLayer = /** @class */ (function () {
  73702. function DebugLayer(scene) {
  73703. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  73704. this._scene = scene;
  73705. // load inspector using require, if it doesn't exist on the global namespace.
  73706. }
  73707. /** Creates the inspector window. */
  73708. DebugLayer.prototype._createInspector = function (config) {
  73709. if (config === void 0) { config = {}; }
  73710. var popup = config.popup || false;
  73711. var initialTab = config.initialTab || 0;
  73712. var parentElement = config.parentElement || null;
  73713. if (!this._inspector) {
  73714. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  73715. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  73716. } // else nothing to do,; instance is already existing
  73717. };
  73718. DebugLayer.prototype.isVisible = function () {
  73719. if (!this._inspector) {
  73720. return false;
  73721. }
  73722. return true;
  73723. };
  73724. DebugLayer.prototype.hide = function () {
  73725. if (this._inspector) {
  73726. try {
  73727. this._inspector.dispose();
  73728. }
  73729. catch (e) {
  73730. // If the inspector has been removed directly from the inspector tool
  73731. }
  73732. this._inspector = null;
  73733. }
  73734. };
  73735. DebugLayer.prototype.show = function (config) {
  73736. if (config === void 0) { config = {}; }
  73737. if (typeof this.BJSINSPECTOR == 'undefined') {
  73738. // Load inspector and add it to the DOM
  73739. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  73740. }
  73741. else {
  73742. // Otherwise creates the inspector
  73743. this._createInspector(config);
  73744. }
  73745. };
  73746. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  73747. return DebugLayer;
  73748. }());
  73749. BABYLON.DebugLayer = DebugLayer;
  73750. })(BABYLON || (BABYLON = {}));
  73751. //# sourceMappingURL=babylon.debugLayer.js.map
  73752. var BABYLON;
  73753. (function (BABYLON) {
  73754. var BoundingBoxRenderer = /** @class */ (function () {
  73755. function BoundingBoxRenderer(scene) {
  73756. this.frontColor = new BABYLON.Color3(1, 1, 1);
  73757. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  73758. this.showBackLines = true;
  73759. this.renderList = new BABYLON.SmartArray(32);
  73760. this._vertexBuffers = {};
  73761. this._scene = scene;
  73762. }
  73763. BoundingBoxRenderer.prototype._prepareRessources = function () {
  73764. if (this._colorShader) {
  73765. return;
  73766. }
  73767. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  73768. attributes: [BABYLON.VertexBuffer.PositionKind],
  73769. uniforms: ["world", "viewProjection", "color"]
  73770. });
  73771. var engine = this._scene.getEngine();
  73772. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  73773. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  73774. this._createIndexBuffer();
  73775. };
  73776. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  73777. var engine = this._scene.getEngine();
  73778. 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]);
  73779. };
  73780. BoundingBoxRenderer.prototype._rebuild = function () {
  73781. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73782. if (vb) {
  73783. vb._rebuild();
  73784. }
  73785. this._createIndexBuffer();
  73786. };
  73787. BoundingBoxRenderer.prototype.reset = function () {
  73788. this.renderList.reset();
  73789. };
  73790. BoundingBoxRenderer.prototype.render = function () {
  73791. if (this.renderList.length === 0) {
  73792. return;
  73793. }
  73794. this._prepareRessources();
  73795. if (!this._colorShader.isReady()) {
  73796. return;
  73797. }
  73798. var engine = this._scene.getEngine();
  73799. engine.setDepthWrite(false);
  73800. this._colorShader._preBind();
  73801. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  73802. var boundingBox = this.renderList.data[boundingBoxIndex];
  73803. var min = boundingBox.minimum;
  73804. var max = boundingBox.maximum;
  73805. var diff = max.subtract(min);
  73806. var median = min.add(diff.scale(0.5));
  73807. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  73808. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  73809. .multiply(boundingBox.getWorldMatrix());
  73810. // VBOs
  73811. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  73812. if (this.showBackLines) {
  73813. // Back
  73814. engine.setDepthFunctionToGreaterOrEqual();
  73815. this._scene.resetCachedMaterial();
  73816. this._colorShader.setColor4("color", this.backColor.toColor4());
  73817. this._colorShader.bind(worldMatrix);
  73818. // Draw order
  73819. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  73820. }
  73821. // Front
  73822. engine.setDepthFunctionToLess();
  73823. this._scene.resetCachedMaterial();
  73824. this._colorShader.setColor4("color", this.frontColor.toColor4());
  73825. this._colorShader.bind(worldMatrix);
  73826. // Draw order
  73827. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  73828. }
  73829. this._colorShader.unbind();
  73830. engine.setDepthFunctionToLessOrEqual();
  73831. engine.setDepthWrite(true);
  73832. };
  73833. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  73834. this._prepareRessources();
  73835. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  73836. return;
  73837. }
  73838. var engine = this._scene.getEngine();
  73839. engine.setDepthWrite(false);
  73840. engine.setColorWrite(false);
  73841. this._colorShader._preBind();
  73842. var boundingBox = mesh._boundingInfo.boundingBox;
  73843. var min = boundingBox.minimum;
  73844. var max = boundingBox.maximum;
  73845. var diff = max.subtract(min);
  73846. var median = min.add(diff.scale(0.5));
  73847. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  73848. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  73849. .multiply(boundingBox.getWorldMatrix());
  73850. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  73851. engine.setDepthFunctionToLess();
  73852. this._scene.resetCachedMaterial();
  73853. this._colorShader.bind(worldMatrix);
  73854. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  73855. this._colorShader.unbind();
  73856. engine.setDepthFunctionToLessOrEqual();
  73857. engine.setDepthWrite(true);
  73858. engine.setColorWrite(true);
  73859. };
  73860. BoundingBoxRenderer.prototype.dispose = function () {
  73861. if (!this._colorShader) {
  73862. return;
  73863. }
  73864. this.renderList.dispose();
  73865. this._colorShader.dispose();
  73866. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73867. if (buffer) {
  73868. buffer.dispose();
  73869. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  73870. }
  73871. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  73872. };
  73873. return BoundingBoxRenderer;
  73874. }());
  73875. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  73876. })(BABYLON || (BABYLON = {}));
  73877. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  73878. var BABYLON;
  73879. (function (BABYLON) {
  73880. var MorphTarget = /** @class */ (function () {
  73881. function MorphTarget(name, influence) {
  73882. if (influence === void 0) { influence = 0; }
  73883. this.name = name;
  73884. this.animations = new Array();
  73885. this._positions = null;
  73886. this._normals = null;
  73887. this._tangents = null;
  73888. this.onInfluenceChanged = new BABYLON.Observable();
  73889. this.influence = influence;
  73890. }
  73891. Object.defineProperty(MorphTarget.prototype, "influence", {
  73892. get: function () {
  73893. return this._influence;
  73894. },
  73895. set: function (influence) {
  73896. if (this._influence === influence) {
  73897. return;
  73898. }
  73899. var previous = this._influence;
  73900. this._influence = influence;
  73901. if (this.onInfluenceChanged.hasObservers) {
  73902. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  73903. }
  73904. },
  73905. enumerable: true,
  73906. configurable: true
  73907. });
  73908. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  73909. get: function () {
  73910. return !!this._positions;
  73911. },
  73912. enumerable: true,
  73913. configurable: true
  73914. });
  73915. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  73916. get: function () {
  73917. return !!this._normals;
  73918. },
  73919. enumerable: true,
  73920. configurable: true
  73921. });
  73922. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  73923. get: function () {
  73924. return !!this._tangents;
  73925. },
  73926. enumerable: true,
  73927. configurable: true
  73928. });
  73929. MorphTarget.prototype.setPositions = function (data) {
  73930. this._positions = data;
  73931. };
  73932. MorphTarget.prototype.getPositions = function () {
  73933. return this._positions;
  73934. };
  73935. MorphTarget.prototype.setNormals = function (data) {
  73936. this._normals = data;
  73937. };
  73938. MorphTarget.prototype.getNormals = function () {
  73939. return this._normals;
  73940. };
  73941. MorphTarget.prototype.setTangents = function (data) {
  73942. this._tangents = data;
  73943. };
  73944. MorphTarget.prototype.getTangents = function () {
  73945. return this._tangents;
  73946. };
  73947. /**
  73948. * Serializes the current target into a Serialization object.
  73949. * Returns the serialized object.
  73950. */
  73951. MorphTarget.prototype.serialize = function () {
  73952. var serializationObject = {};
  73953. serializationObject.name = this.name;
  73954. serializationObject.influence = this.influence;
  73955. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  73956. if (this.hasNormals) {
  73957. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  73958. }
  73959. if (this.hasTangents) {
  73960. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  73961. }
  73962. // Animations
  73963. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  73964. return serializationObject;
  73965. };
  73966. // Statics
  73967. MorphTarget.Parse = function (serializationObject) {
  73968. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  73969. result.setPositions(serializationObject.positions);
  73970. if (serializationObject.normals) {
  73971. result.setNormals(serializationObject.normals);
  73972. }
  73973. if (serializationObject.tangents) {
  73974. result.setTangents(serializationObject.tangents);
  73975. }
  73976. // Animations
  73977. if (serializationObject.animations) {
  73978. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  73979. var parsedAnimation = serializationObject.animations[animationIndex];
  73980. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  73981. }
  73982. }
  73983. return result;
  73984. };
  73985. MorphTarget.FromMesh = function (mesh, name, influence) {
  73986. if (!name) {
  73987. name = mesh.name;
  73988. }
  73989. var result = new MorphTarget(name, influence);
  73990. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  73991. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  73992. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  73993. }
  73994. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  73995. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  73996. }
  73997. return result;
  73998. };
  73999. return MorphTarget;
  74000. }());
  74001. BABYLON.MorphTarget = MorphTarget;
  74002. })(BABYLON || (BABYLON = {}));
  74003. //# sourceMappingURL=babylon.morphTarget.js.map
  74004. var BABYLON;
  74005. (function (BABYLON) {
  74006. var MorphTargetManager = /** @class */ (function () {
  74007. function MorphTargetManager(scene) {
  74008. if (scene === void 0) { scene = null; }
  74009. this._targets = new Array();
  74010. this._targetObservable = new Array();
  74011. this._activeTargets = new BABYLON.SmartArray(16);
  74012. this._supportsNormals = false;
  74013. this._supportsTangents = false;
  74014. this._vertexCount = 0;
  74015. this._uniqueId = 0;
  74016. this._tempInfluences = new Array();
  74017. if (!scene) {
  74018. scene = BABYLON.Engine.LastCreatedScene;
  74019. }
  74020. this._scene = scene;
  74021. if (this._scene) {
  74022. this._scene.morphTargetManagers.push(this);
  74023. this._uniqueId = this._scene.getUniqueId();
  74024. }
  74025. }
  74026. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  74027. get: function () {
  74028. return this._uniqueId;
  74029. },
  74030. enumerable: true,
  74031. configurable: true
  74032. });
  74033. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  74034. get: function () {
  74035. return this._vertexCount;
  74036. },
  74037. enumerable: true,
  74038. configurable: true
  74039. });
  74040. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  74041. get: function () {
  74042. return this._supportsNormals;
  74043. },
  74044. enumerable: true,
  74045. configurable: true
  74046. });
  74047. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  74048. get: function () {
  74049. return this._supportsTangents;
  74050. },
  74051. enumerable: true,
  74052. configurable: true
  74053. });
  74054. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  74055. get: function () {
  74056. return this._targets.length;
  74057. },
  74058. enumerable: true,
  74059. configurable: true
  74060. });
  74061. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  74062. get: function () {
  74063. return this._activeTargets.length;
  74064. },
  74065. enumerable: true,
  74066. configurable: true
  74067. });
  74068. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  74069. get: function () {
  74070. return this._influences;
  74071. },
  74072. enumerable: true,
  74073. configurable: true
  74074. });
  74075. MorphTargetManager.prototype.getActiveTarget = function (index) {
  74076. return this._activeTargets.data[index];
  74077. };
  74078. MorphTargetManager.prototype.getTarget = function (index) {
  74079. return this._targets[index];
  74080. };
  74081. MorphTargetManager.prototype.addTarget = function (target) {
  74082. var _this = this;
  74083. this._targets.push(target);
  74084. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  74085. _this._syncActiveTargets(needUpdate);
  74086. }));
  74087. this._syncActiveTargets(true);
  74088. };
  74089. MorphTargetManager.prototype.removeTarget = function (target) {
  74090. var index = this._targets.indexOf(target);
  74091. if (index >= 0) {
  74092. this._targets.splice(index, 1);
  74093. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  74094. this._syncActiveTargets(true);
  74095. }
  74096. };
  74097. /**
  74098. * Serializes the current manager into a Serialization object.
  74099. * Returns the serialized object.
  74100. */
  74101. MorphTargetManager.prototype.serialize = function () {
  74102. var serializationObject = {};
  74103. serializationObject.id = this.uniqueId;
  74104. serializationObject.targets = [];
  74105. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  74106. var target = _a[_i];
  74107. serializationObject.targets.push(target.serialize());
  74108. }
  74109. return serializationObject;
  74110. };
  74111. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  74112. var influenceCount = 0;
  74113. this._activeTargets.reset();
  74114. this._supportsNormals = true;
  74115. this._supportsTangents = true;
  74116. this._vertexCount = 0;
  74117. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  74118. var target = _a[_i];
  74119. this._activeTargets.push(target);
  74120. this._tempInfluences[influenceCount++] = target.influence;
  74121. var positions = target.getPositions();
  74122. if (positions) {
  74123. this._supportsNormals = this._supportsNormals && target.hasNormals;
  74124. this._supportsTangents = this._supportsTangents && target.hasTangents;
  74125. var vertexCount = positions.length / 3;
  74126. if (this._vertexCount === 0) {
  74127. this._vertexCount = vertexCount;
  74128. }
  74129. else if (this._vertexCount !== vertexCount) {
  74130. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  74131. return;
  74132. }
  74133. }
  74134. }
  74135. if (!this._influences || this._influences.length !== influenceCount) {
  74136. this._influences = new Float32Array(influenceCount);
  74137. }
  74138. for (var index = 0; index < influenceCount; index++) {
  74139. this._influences[index] = this._tempInfluences[index];
  74140. }
  74141. if (needUpdate && this._scene) {
  74142. // Flag meshes as dirty to resync with the active targets
  74143. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  74144. var mesh = _c[_b];
  74145. if (mesh.morphTargetManager === this) {
  74146. mesh._syncGeometryWithMorphTargetManager();
  74147. }
  74148. }
  74149. }
  74150. };
  74151. // Statics
  74152. MorphTargetManager.Parse = function (serializationObject, scene) {
  74153. var result = new MorphTargetManager(scene);
  74154. result._uniqueId = serializationObject.id;
  74155. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  74156. var targetData = _a[_i];
  74157. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  74158. }
  74159. return result;
  74160. };
  74161. return MorphTargetManager;
  74162. }());
  74163. BABYLON.MorphTargetManager = MorphTargetManager;
  74164. })(BABYLON || (BABYLON = {}));
  74165. //# sourceMappingURL=babylon.morphTargetManager.js.map
  74166. var BABYLON;
  74167. (function (BABYLON) {
  74168. var Octree = /** @class */ (function () {
  74169. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  74170. if (maxDepth === void 0) { maxDepth = 2; }
  74171. this.maxDepth = maxDepth;
  74172. this.dynamicContent = new Array();
  74173. this._maxBlockCapacity = maxBlockCapacity || 64;
  74174. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  74175. this._creationFunc = creationFunc;
  74176. }
  74177. // Methods
  74178. Octree.prototype.update = function (worldMin, worldMax, entries) {
  74179. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  74180. };
  74181. Octree.prototype.addMesh = function (entry) {
  74182. for (var index = 0; index < this.blocks.length; index++) {
  74183. var block = this.blocks[index];
  74184. block.addEntry(entry);
  74185. }
  74186. };
  74187. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  74188. this._selectionContent.reset();
  74189. for (var index = 0; index < this.blocks.length; index++) {
  74190. var block = this.blocks[index];
  74191. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  74192. }
  74193. if (allowDuplicate) {
  74194. this._selectionContent.concat(this.dynamicContent);
  74195. }
  74196. else {
  74197. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  74198. }
  74199. return this._selectionContent;
  74200. };
  74201. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  74202. this._selectionContent.reset();
  74203. for (var index = 0; index < this.blocks.length; index++) {
  74204. var block = this.blocks[index];
  74205. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  74206. }
  74207. if (allowDuplicate) {
  74208. this._selectionContent.concat(this.dynamicContent);
  74209. }
  74210. else {
  74211. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  74212. }
  74213. return this._selectionContent;
  74214. };
  74215. Octree.prototype.intersectsRay = function (ray) {
  74216. this._selectionContent.reset();
  74217. for (var index = 0; index < this.blocks.length; index++) {
  74218. var block = this.blocks[index];
  74219. block.intersectsRay(ray, this._selectionContent);
  74220. }
  74221. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  74222. return this._selectionContent;
  74223. };
  74224. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  74225. target.blocks = new Array();
  74226. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  74227. // Segmenting space
  74228. for (var x = 0; x < 2; x++) {
  74229. for (var y = 0; y < 2; y++) {
  74230. for (var z = 0; z < 2; z++) {
  74231. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  74232. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  74233. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  74234. block.addEntries(entries);
  74235. target.blocks.push(block);
  74236. }
  74237. }
  74238. }
  74239. };
  74240. Octree.CreationFuncForMeshes = function (entry, block) {
  74241. var boundingInfo = entry.getBoundingInfo();
  74242. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  74243. block.entries.push(entry);
  74244. }
  74245. };
  74246. Octree.CreationFuncForSubMeshes = function (entry, block) {
  74247. var boundingInfo = entry.getBoundingInfo();
  74248. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  74249. block.entries.push(entry);
  74250. }
  74251. };
  74252. return Octree;
  74253. }());
  74254. BABYLON.Octree = Octree;
  74255. })(BABYLON || (BABYLON = {}));
  74256. //# sourceMappingURL=babylon.octree.js.map
  74257. var BABYLON;
  74258. (function (BABYLON) {
  74259. var OctreeBlock = /** @class */ (function () {
  74260. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  74261. this.entries = new Array();
  74262. this._boundingVectors = new Array();
  74263. this._capacity = capacity;
  74264. this._depth = depth;
  74265. this._maxDepth = maxDepth;
  74266. this._creationFunc = creationFunc;
  74267. this._minPoint = minPoint;
  74268. this._maxPoint = maxPoint;
  74269. this._boundingVectors.push(minPoint.clone());
  74270. this._boundingVectors.push(maxPoint.clone());
  74271. this._boundingVectors.push(minPoint.clone());
  74272. this._boundingVectors[2].x = maxPoint.x;
  74273. this._boundingVectors.push(minPoint.clone());
  74274. this._boundingVectors[3].y = maxPoint.y;
  74275. this._boundingVectors.push(minPoint.clone());
  74276. this._boundingVectors[4].z = maxPoint.z;
  74277. this._boundingVectors.push(maxPoint.clone());
  74278. this._boundingVectors[5].z = minPoint.z;
  74279. this._boundingVectors.push(maxPoint.clone());
  74280. this._boundingVectors[6].x = minPoint.x;
  74281. this._boundingVectors.push(maxPoint.clone());
  74282. this._boundingVectors[7].y = minPoint.y;
  74283. }
  74284. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  74285. // Property
  74286. get: function () {
  74287. return this._capacity;
  74288. },
  74289. enumerable: true,
  74290. configurable: true
  74291. });
  74292. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  74293. get: function () {
  74294. return this._minPoint;
  74295. },
  74296. enumerable: true,
  74297. configurable: true
  74298. });
  74299. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  74300. get: function () {
  74301. return this._maxPoint;
  74302. },
  74303. enumerable: true,
  74304. configurable: true
  74305. });
  74306. // Methods
  74307. OctreeBlock.prototype.addEntry = function (entry) {
  74308. if (this.blocks) {
  74309. for (var index = 0; index < this.blocks.length; index++) {
  74310. var block = this.blocks[index];
  74311. block.addEntry(entry);
  74312. }
  74313. return;
  74314. }
  74315. this._creationFunc(entry, this);
  74316. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  74317. this.createInnerBlocks();
  74318. }
  74319. };
  74320. OctreeBlock.prototype.addEntries = function (entries) {
  74321. for (var index = 0; index < entries.length; index++) {
  74322. var mesh = entries[index];
  74323. this.addEntry(mesh);
  74324. }
  74325. };
  74326. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  74327. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  74328. if (this.blocks) {
  74329. for (var index = 0; index < this.blocks.length; index++) {
  74330. var block = this.blocks[index];
  74331. block.select(frustumPlanes, selection, allowDuplicate);
  74332. }
  74333. return;
  74334. }
  74335. if (allowDuplicate) {
  74336. selection.concat(this.entries);
  74337. }
  74338. else {
  74339. selection.concatWithNoDuplicate(this.entries);
  74340. }
  74341. }
  74342. };
  74343. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  74344. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  74345. if (this.blocks) {
  74346. for (var index = 0; index < this.blocks.length; index++) {
  74347. var block = this.blocks[index];
  74348. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  74349. }
  74350. return;
  74351. }
  74352. if (allowDuplicate) {
  74353. selection.concat(this.entries);
  74354. }
  74355. else {
  74356. selection.concatWithNoDuplicate(this.entries);
  74357. }
  74358. }
  74359. };
  74360. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  74361. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  74362. if (this.blocks) {
  74363. for (var index = 0; index < this.blocks.length; index++) {
  74364. var block = this.blocks[index];
  74365. block.intersectsRay(ray, selection);
  74366. }
  74367. return;
  74368. }
  74369. selection.concatWithNoDuplicate(this.entries);
  74370. }
  74371. };
  74372. OctreeBlock.prototype.createInnerBlocks = function () {
  74373. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  74374. };
  74375. return OctreeBlock;
  74376. }());
  74377. BABYLON.OctreeBlock = OctreeBlock;
  74378. })(BABYLON || (BABYLON = {}));
  74379. //# sourceMappingURL=babylon.octreeBlock.js.map
  74380. var BABYLON;
  74381. (function (BABYLON) {
  74382. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  74383. __extends(VRDistortionCorrectionPostProcess, _super);
  74384. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  74385. var _this = _super.call(this, name, "vrDistortionCorrection", [
  74386. 'LensCenter',
  74387. 'Scale',
  74388. 'ScaleIn',
  74389. 'HmdWarpParam'
  74390. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  74391. _this._isRightEye = isRightEye;
  74392. _this._distortionFactors = vrMetrics.distortionK;
  74393. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  74394. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  74395. _this.adaptScaleToCurrentViewport = true;
  74396. _this.onSizeChangedObservable.add(function () {
  74397. _this.aspectRatio = _this.width * .5 / _this.height;
  74398. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  74399. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  74400. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  74401. });
  74402. _this.onApplyObservable.add(function (effect) {
  74403. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  74404. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  74405. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  74406. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  74407. });
  74408. return _this;
  74409. }
  74410. return VRDistortionCorrectionPostProcess;
  74411. }(BABYLON.PostProcess));
  74412. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  74413. })(BABYLON || (BABYLON = {}));
  74414. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  74415. var BABYLON;
  74416. (function (BABYLON) {
  74417. var AnaglyphPostProcess = /** @class */ (function (_super) {
  74418. __extends(AnaglyphPostProcess, _super);
  74419. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  74420. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  74421. _this._passedProcess = rigCameras[0]._rigPostProcess;
  74422. _this.onApplyObservable.add(function (effect) {
  74423. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  74424. });
  74425. return _this;
  74426. }
  74427. return AnaglyphPostProcess;
  74428. }(BABYLON.PostProcess));
  74429. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  74430. })(BABYLON || (BABYLON = {}));
  74431. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  74432. var BABYLON;
  74433. (function (BABYLON) {
  74434. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  74435. __extends(StereoscopicInterlacePostProcess, _super);
  74436. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  74437. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  74438. _this._passedProcess = rigCameras[0]._rigPostProcess;
  74439. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  74440. _this.onSizeChangedObservable.add(function () {
  74441. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  74442. });
  74443. _this.onApplyObservable.add(function (effect) {
  74444. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  74445. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  74446. });
  74447. return _this;
  74448. }
  74449. return StereoscopicInterlacePostProcess;
  74450. }(BABYLON.PostProcess));
  74451. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  74452. })(BABYLON || (BABYLON = {}));
  74453. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  74454. var BABYLON;
  74455. (function (BABYLON) {
  74456. /**
  74457. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  74458. * Screen rotation is taken into account.
  74459. */
  74460. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  74461. function FreeCameraDeviceOrientationInput() {
  74462. var _this = this;
  74463. this._screenOrientationAngle = 0;
  74464. this._screenQuaternion = new BABYLON.Quaternion();
  74465. this._alpha = 0;
  74466. this._beta = 0;
  74467. this._gamma = 0;
  74468. this._orientationChanged = function () {
  74469. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  74470. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  74471. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  74472. };
  74473. this._deviceOrientation = function (evt) {
  74474. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  74475. _this._beta = evt.beta !== null ? evt.beta : 0;
  74476. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  74477. };
  74478. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  74479. this._orientationChanged();
  74480. }
  74481. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  74482. get: function () {
  74483. return this._camera;
  74484. },
  74485. set: function (camera) {
  74486. this._camera = camera;
  74487. if (this._camera != null && !this._camera.rotationQuaternion) {
  74488. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  74489. }
  74490. },
  74491. enumerable: true,
  74492. configurable: true
  74493. });
  74494. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  74495. window.addEventListener("orientationchange", this._orientationChanged);
  74496. window.addEventListener("deviceorientation", this._deviceOrientation);
  74497. //In certain cases, the attach control is called AFTER orientation was changed,
  74498. //So this is needed.
  74499. this._orientationChanged();
  74500. };
  74501. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  74502. window.removeEventListener("orientationchange", this._orientationChanged);
  74503. window.removeEventListener("deviceorientation", this._deviceOrientation);
  74504. };
  74505. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  74506. //if no device orientation provided, don't update the rotation.
  74507. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  74508. if (!this._alpha)
  74509. return;
  74510. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  74511. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  74512. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  74513. //Mirror on XY Plane
  74514. this._camera.rotationQuaternion.z *= -1;
  74515. this._camera.rotationQuaternion.w *= -1;
  74516. };
  74517. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  74518. return "FreeCameraDeviceOrientationInput";
  74519. };
  74520. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  74521. return "deviceOrientation";
  74522. };
  74523. return FreeCameraDeviceOrientationInput;
  74524. }());
  74525. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  74526. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  74527. })(BABYLON || (BABYLON = {}));
  74528. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  74529. var BABYLON;
  74530. (function (BABYLON) {
  74531. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  74532. function ArcRotateCameraVRDeviceOrientationInput() {
  74533. this.alphaCorrection = 1;
  74534. this.betaCorrection = 1;
  74535. this.gammaCorrection = 1;
  74536. this._alpha = 0;
  74537. this._gamma = 0;
  74538. this._dirty = false;
  74539. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  74540. }
  74541. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  74542. this.camera.attachControl(element, noPreventDefault);
  74543. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  74544. };
  74545. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  74546. if (evt.alpha !== null) {
  74547. this._alpha = +evt.alpha | 0;
  74548. }
  74549. if (evt.gamma !== null) {
  74550. this._gamma = +evt.gamma | 0;
  74551. }
  74552. this._dirty = true;
  74553. };
  74554. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  74555. if (this._dirty) {
  74556. this._dirty = false;
  74557. if (this._gamma < 0) {
  74558. this._gamma = 180 + this._gamma;
  74559. }
  74560. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  74561. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  74562. }
  74563. };
  74564. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  74565. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  74566. };
  74567. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  74568. return "ArcRotateCameraVRDeviceOrientationInput";
  74569. };
  74570. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  74571. return "VRDeviceOrientation";
  74572. };
  74573. return ArcRotateCameraVRDeviceOrientationInput;
  74574. }());
  74575. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  74576. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  74577. })(BABYLON || (BABYLON = {}));
  74578. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  74579. var BABYLON;
  74580. (function (BABYLON) {
  74581. var VRCameraMetrics = /** @class */ (function () {
  74582. function VRCameraMetrics() {
  74583. this.compensateDistortion = true;
  74584. }
  74585. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  74586. get: function () {
  74587. return this.hResolution / (2 * this.vResolution);
  74588. },
  74589. enumerable: true,
  74590. configurable: true
  74591. });
  74592. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  74593. get: function () {
  74594. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  74595. },
  74596. enumerable: true,
  74597. configurable: true
  74598. });
  74599. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  74600. get: function () {
  74601. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  74602. var h = (4 * meters) / this.hScreenSize;
  74603. return BABYLON.Matrix.Translation(h, 0, 0);
  74604. },
  74605. enumerable: true,
  74606. configurable: true
  74607. });
  74608. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  74609. get: function () {
  74610. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  74611. var h = (4 * meters) / this.hScreenSize;
  74612. return BABYLON.Matrix.Translation(-h, 0, 0);
  74613. },
  74614. enumerable: true,
  74615. configurable: true
  74616. });
  74617. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  74618. get: function () {
  74619. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  74620. },
  74621. enumerable: true,
  74622. configurable: true
  74623. });
  74624. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  74625. get: function () {
  74626. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  74627. },
  74628. enumerable: true,
  74629. configurable: true
  74630. });
  74631. VRCameraMetrics.GetDefault = function () {
  74632. var result = new VRCameraMetrics();
  74633. result.hResolution = 1280;
  74634. result.vResolution = 800;
  74635. result.hScreenSize = 0.149759993;
  74636. result.vScreenSize = 0.0935999975;
  74637. result.vScreenCenter = 0.0467999987;
  74638. result.eyeToScreenDistance = 0.0410000011;
  74639. result.lensSeparationDistance = 0.0635000020;
  74640. result.interpupillaryDistance = 0.0640000030;
  74641. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  74642. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  74643. result.postProcessScaleFactor = 1.714605507808412;
  74644. result.lensCenterOffset = 0.151976421;
  74645. return result;
  74646. };
  74647. return VRCameraMetrics;
  74648. }());
  74649. BABYLON.VRCameraMetrics = VRCameraMetrics;
  74650. })(BABYLON || (BABYLON = {}));
  74651. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  74652. var BABYLON;
  74653. (function (BABYLON) {
  74654. /**
  74655. * This represents a WebVR camera.
  74656. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  74657. * @example http://doc.babylonjs.com/how_to/webvr_camera
  74658. */
  74659. var WebVRFreeCamera = /** @class */ (function (_super) {
  74660. __extends(WebVRFreeCamera, _super);
  74661. /**
  74662. * Instantiates a WebVRFreeCamera.
  74663. * @param name The name of the WebVRFreeCamera
  74664. * @param position The starting anchor position for the camera
  74665. * @param scene The scene the camera belongs to
  74666. * @param webVROptions a set of customizable options for the webVRCamera
  74667. */
  74668. function WebVRFreeCamera(name, position, scene, webVROptions) {
  74669. if (webVROptions === void 0) { webVROptions = {}; }
  74670. var _this = _super.call(this, name, position, scene) || this;
  74671. _this.webVROptions = webVROptions;
  74672. /**
  74673. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  74674. */
  74675. _this._vrDevice = null;
  74676. /**
  74677. * The rawPose of the vrDevice.
  74678. */
  74679. _this.rawPose = null;
  74680. _this._specsVersion = "1.1";
  74681. _this._attached = false;
  74682. _this._descendants = [];
  74683. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  74684. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  74685. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  74686. _this._standingMatrix = null;
  74687. /**
  74688. * Represents device position in babylon space.
  74689. */
  74690. _this.devicePosition = BABYLON.Vector3.Zero();
  74691. /**
  74692. * Represents device rotation in babylon space.
  74693. */
  74694. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  74695. /**
  74696. * The scale of the device to be used when translating from device space to babylon space.
  74697. */
  74698. _this.deviceScaleFactor = 1;
  74699. _this._deviceToWorld = BABYLON.Matrix.Identity();
  74700. _this._worldToDevice = BABYLON.Matrix.Identity();
  74701. /**
  74702. * References to the webVR controllers for the vrDevice.
  74703. */
  74704. _this.controllers = [];
  74705. /**
  74706. * Emits an event when a controller is attached.
  74707. */
  74708. _this.onControllersAttachedObservable = new BABYLON.Observable();
  74709. /**
  74710. * Emits an event when a controller's mesh has been loaded;
  74711. */
  74712. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  74713. /**
  74714. * If the rig cameras be used as parent instead of this camera.
  74715. */
  74716. _this.rigParenting = true;
  74717. _this._defaultHeight = undefined;
  74718. _this._workingVector = BABYLON.Vector3.Zero();
  74719. _this._oneVector = BABYLON.Vector3.One();
  74720. _this._workingMatrix = BABYLON.Matrix.Identity();
  74721. _this._cache.position = BABYLON.Vector3.Zero();
  74722. if (webVROptions.defaultHeight) {
  74723. _this._defaultHeight = webVROptions.defaultHeight;
  74724. _this.position.y = _this._defaultHeight;
  74725. }
  74726. _this.minZ = 0.1;
  74727. //legacy support - the compensation boolean was removed.
  74728. if (arguments.length === 5) {
  74729. _this.webVROptions = arguments[4];
  74730. }
  74731. // default webVR options
  74732. if (_this.webVROptions.trackPosition == undefined) {
  74733. _this.webVROptions.trackPosition = true;
  74734. }
  74735. if (_this.webVROptions.controllerMeshes == undefined) {
  74736. _this.webVROptions.controllerMeshes = true;
  74737. }
  74738. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  74739. _this.webVROptions.defaultLightingOnControllers = true;
  74740. }
  74741. _this.rotationQuaternion = new BABYLON.Quaternion();
  74742. if (_this.webVROptions && _this.webVROptions.positionScale) {
  74743. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  74744. }
  74745. //enable VR
  74746. var engine = _this.getEngine();
  74747. _this._onVREnabled = function (success) { if (success) {
  74748. _this.initControllers();
  74749. } };
  74750. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  74751. engine.initWebVR().add(function (event) {
  74752. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  74753. return;
  74754. }
  74755. _this._vrDevice = event.vrDisplay;
  74756. //reset the rig parameters.
  74757. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  74758. if (_this._attached) {
  74759. _this.getEngine().enableVR();
  74760. }
  74761. });
  74762. if (typeof (VRFrameData) !== "undefined")
  74763. _this._frameData = new VRFrameData();
  74764. /**
  74765. * The idea behind the following lines:
  74766. * objects that have the camera as parent should actually have the rig cameras as a parent.
  74767. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  74768. * the second will not show it correctly.
  74769. *
  74770. * To solve this - each object that has the camera as parent will be added to a protected array.
  74771. * When the rig camera renders, it will take this array and set all of those to be its children.
  74772. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  74773. * Amazing!
  74774. */
  74775. scene.onBeforeCameraRenderObservable.add(function (camera) {
  74776. if (camera.parent === _this && _this.rigParenting) {
  74777. _this._descendants = _this.getDescendants(true, function (n) {
  74778. // don't take the cameras or the controllers!
  74779. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  74780. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  74781. return !isController && !isRigCamera;
  74782. });
  74783. _this._descendants.forEach(function (node) {
  74784. node.parent = camera;
  74785. });
  74786. }
  74787. });
  74788. scene.onAfterCameraRenderObservable.add(function (camera) {
  74789. if (camera.parent === _this && _this.rigParenting) {
  74790. _this._descendants.forEach(function (node) {
  74791. node.parent = _this;
  74792. });
  74793. }
  74794. });
  74795. return _this;
  74796. }
  74797. /**
  74798. * Gets the device distance from the ground.
  74799. * @returns the distance from the vrDevice to ground in device space. If standing matrix is not supported for the vrDevice 0 is returned.
  74800. */
  74801. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  74802. if (this._standingMatrix && this._defaultHeight === undefined) {
  74803. // Add standing matrix offset to get real offset from ground in room
  74804. this._standingMatrix.getTranslationToRef(this._workingVector);
  74805. return this._deviceRoomPosition.y + this._workingVector.y;
  74806. }
  74807. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  74808. return this._defaultHeight || 0;
  74809. };
  74810. /**
  74811. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  74812. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  74813. */
  74814. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  74815. var _this = this;
  74816. if (callback === void 0) { callback = function (bool) { }; }
  74817. // Use standing matrix if available
  74818. if (!navigator || !navigator.getVRDisplays) {
  74819. callback(false);
  74820. }
  74821. else {
  74822. navigator.getVRDisplays().then(function (displays) {
  74823. if (!displays || !displays[0] || !displays[0].stageParameters || !displays[0].stageParameters.sittingToStandingTransform) {
  74824. callback(false);
  74825. }
  74826. else {
  74827. _this._standingMatrix = new BABYLON.Matrix();
  74828. BABYLON.Matrix.FromFloat32ArrayToRefScaled(displays[0].stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  74829. if (!_this.getScene().useRightHandedSystem) {
  74830. [2, 6, 8, 9, 14].forEach(function (num) {
  74831. if (_this._standingMatrix) {
  74832. _this._standingMatrix.m[num] *= -1;
  74833. }
  74834. });
  74835. }
  74836. callback(true);
  74837. }
  74838. });
  74839. }
  74840. };
  74841. /**
  74842. * Disposes the camera
  74843. */
  74844. WebVRFreeCamera.prototype.dispose = function () {
  74845. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  74846. _super.prototype.dispose.call(this);
  74847. };
  74848. /**
  74849. * Gets a vrController by name.
  74850. * @param name The name of the controller to retreive
  74851. * @returns the controller matching the name specified or null if not found
  74852. */
  74853. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  74854. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  74855. var gp = _a[_i];
  74856. if (gp.hand === name) {
  74857. return gp;
  74858. }
  74859. }
  74860. return null;
  74861. };
  74862. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  74863. /**
  74864. * The controller corrisponding to the users left hand.
  74865. */
  74866. get: function () {
  74867. if (!this._leftController) {
  74868. this._leftController = this.getControllerByName("left");
  74869. }
  74870. return this._leftController;
  74871. },
  74872. enumerable: true,
  74873. configurable: true
  74874. });
  74875. ;
  74876. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  74877. /**
  74878. * The controller corrisponding to the users right hand.
  74879. */
  74880. get: function () {
  74881. if (!this._rightController) {
  74882. this._rightController = this.getControllerByName("right");
  74883. }
  74884. return this._rightController;
  74885. },
  74886. enumerable: true,
  74887. configurable: true
  74888. });
  74889. ;
  74890. /**
  74891. * Casts a ray forward from the vrCamera's gaze.
  74892. * @param length Length of the ray (default: 100)
  74893. * @returns the ray corrisponding to the gaze
  74894. */
  74895. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  74896. if (length === void 0) { length = 100; }
  74897. if (this.leftCamera) {
  74898. // Use left eye to avoid computation to compute center on every call
  74899. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  74900. }
  74901. else {
  74902. return _super.prototype.getForwardRay.call(this, length);
  74903. }
  74904. };
  74905. /**
  74906. * Updates the camera based on device's frame data
  74907. */
  74908. WebVRFreeCamera.prototype._checkInputs = function () {
  74909. if (this._vrDevice && this._vrDevice.isPresenting) {
  74910. this._vrDevice.getFrameData(this._frameData);
  74911. this.updateFromDevice(this._frameData.pose);
  74912. }
  74913. _super.prototype._checkInputs.call(this);
  74914. };
  74915. /**
  74916. * Updates the poseControlled values based on the input device pose.
  74917. * @param poseData Pose coming from the device
  74918. */
  74919. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  74920. if (poseData && poseData.orientation) {
  74921. this.rawPose = poseData;
  74922. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  74923. if (this.getScene().useRightHandedSystem) {
  74924. this._deviceRoomRotationQuaternion.z *= -1;
  74925. this._deviceRoomRotationQuaternion.w *= -1;
  74926. }
  74927. if (this.webVROptions.trackPosition && this.rawPose.position) {
  74928. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  74929. if (this.getScene().useRightHandedSystem) {
  74930. this._deviceRoomPosition.z *= -1;
  74931. }
  74932. }
  74933. }
  74934. };
  74935. /**
  74936. * WebVR's attach control will start broadcasting frames to the device.
  74937. * Note that in certain browsers (chrome for example) this function must be called
  74938. * within a user-interaction callback. Example:
  74939. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  74940. *
  74941. * @param element html element to attach the vrDevice to
  74942. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  74943. */
  74944. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  74945. _super.prototype.attachControl.call(this, element, noPreventDefault);
  74946. this._attached = true;
  74947. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  74948. if (this._vrDevice) {
  74949. this.getEngine().enableVR();
  74950. }
  74951. };
  74952. /**
  74953. * Detaches the camera from the html element and disables VR
  74954. *
  74955. * @param element html element to detach from
  74956. */
  74957. WebVRFreeCamera.prototype.detachControl = function (element) {
  74958. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  74959. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  74960. _super.prototype.detachControl.call(this, element);
  74961. this._attached = false;
  74962. this.getEngine().disableVR();
  74963. };
  74964. /**
  74965. * @returns the name of this class
  74966. */
  74967. WebVRFreeCamera.prototype.getClassName = function () {
  74968. return "WebVRFreeCamera";
  74969. };
  74970. /**
  74971. * Calls resetPose on the vrDisplay
  74972. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  74973. */
  74974. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  74975. //uses the vrDisplay's "resetPose()".
  74976. //pitch and roll won't be affected.
  74977. this._vrDevice.resetPose();
  74978. };
  74979. /**
  74980. * Updates the rig cameras (left and right eye)
  74981. */
  74982. WebVRFreeCamera.prototype._updateRigCameras = function () {
  74983. var camLeft = this._rigCameras[0];
  74984. var camRight = this._rigCameras[1];
  74985. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  74986. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  74987. camLeft.position.copyFrom(this._deviceRoomPosition);
  74988. camRight.position.copyFrom(this._deviceRoomPosition);
  74989. };
  74990. /**
  74991. * Updates the cached values of the camera
  74992. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  74993. */
  74994. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  74995. var _this = this;
  74996. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  74997. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  74998. if (!this.updateCacheCalled) {
  74999. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  75000. this.updateCacheCalled = true;
  75001. this.update();
  75002. }
  75003. // Set working vector to the device position in room space rotated by the new rotation
  75004. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  75005. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  75006. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  75007. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  75008. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  75009. // Add translation from anchor position
  75010. this._deviceToWorld.getTranslationToRef(this._workingVector);
  75011. this._workingVector.addInPlace(this.position);
  75012. this._workingVector.subtractInPlace(this._cache.position);
  75013. this._deviceToWorld.setTranslation(this._workingVector);
  75014. // Set an inverted matrix to be used when updating the camera
  75015. this._deviceToWorld.invertToRef(this._worldToDevice);
  75016. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  75017. this.controllers.forEach(function (controller) {
  75018. controller._deviceToWorld = _this._deviceToWorld;
  75019. controller.update();
  75020. });
  75021. }
  75022. if (!ignoreParentClass) {
  75023. _super.prototype._updateCache.call(this);
  75024. }
  75025. this.updateCacheCalled = false;
  75026. };
  75027. /**
  75028. * Updates the current device position and rotation in the babylon world
  75029. */
  75030. WebVRFreeCamera.prototype.update = function () {
  75031. // Get current device position in babylon world
  75032. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  75033. // Get current device rotation in babylon world
  75034. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  75035. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  75036. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  75037. _super.prototype.update.call(this);
  75038. };
  75039. /**
  75040. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  75041. * @returns an identity matrix
  75042. */
  75043. WebVRFreeCamera.prototype._getViewMatrix = function () {
  75044. return BABYLON.Matrix.Identity();
  75045. };
  75046. /**
  75047. * This function is called by the two RIG cameras.
  75048. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  75049. */
  75050. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  75051. var _this = this;
  75052. //WebVR 1.1
  75053. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  75054. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  75055. if (!this.getScene().useRightHandedSystem) {
  75056. [2, 6, 8, 9, 14].forEach(function (num) {
  75057. _this._webvrViewMatrix.m[num] *= -1;
  75058. });
  75059. }
  75060. // update the camera rotation matrix
  75061. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  75062. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  75063. // Computing target and final matrix
  75064. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  75065. var parentCamera = this._cameraRigParams["parentCamera"];
  75066. // should the view matrix be updated with scale and position offset?
  75067. if (parentCamera.deviceScaleFactor !== 1) {
  75068. this._webvrViewMatrix.invert();
  75069. // scale the position, if set
  75070. if (parentCamera.deviceScaleFactor) {
  75071. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  75072. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  75073. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  75074. }
  75075. this._webvrViewMatrix.invert();
  75076. }
  75077. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  75078. return this._webvrViewMatrix;
  75079. };
  75080. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  75081. var _this = this;
  75082. var parentCamera = this.parent;
  75083. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  75084. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  75085. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  75086. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  75087. //babylon compatible matrix
  75088. if (!this.getScene().useRightHandedSystem) {
  75089. [8, 9, 10, 11].forEach(function (num) {
  75090. _this._projectionMatrix.m[num] *= -1;
  75091. });
  75092. }
  75093. return this._projectionMatrix;
  75094. };
  75095. /**
  75096. * Initializes the controllers and their meshes
  75097. */
  75098. WebVRFreeCamera.prototype.initControllers = function () {
  75099. var _this = this;
  75100. this.controllers = [];
  75101. var manager = this.getScene().gamepadManager;
  75102. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  75103. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  75104. var webVrController = gamepad;
  75105. if (webVrController.defaultModel) {
  75106. webVrController.defaultModel.setEnabled(false);
  75107. }
  75108. if (webVrController.hand === "right") {
  75109. _this._rightController = null;
  75110. }
  75111. if (webVrController.hand === "left") {
  75112. _this._rightController = null;
  75113. }
  75114. var controllerIndex = _this.controllers.indexOf(webVrController);
  75115. if (controllerIndex !== -1) {
  75116. _this.controllers.splice(controllerIndex, 1);
  75117. }
  75118. }
  75119. });
  75120. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  75121. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  75122. var webVrController_1 = gamepad;
  75123. webVrController_1._deviceToWorld = _this._deviceToWorld;
  75124. if (_this.webVROptions.controllerMeshes) {
  75125. if (webVrController_1.defaultModel) {
  75126. webVrController_1.defaultModel.setEnabled(true);
  75127. }
  75128. else {
  75129. // Load the meshes
  75130. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  75131. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  75132. if (_this.webVROptions.defaultLightingOnControllers) {
  75133. if (!_this._lightOnControllers) {
  75134. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  75135. }
  75136. var activateLightOnSubMeshes_1 = function (mesh, light) {
  75137. var children = mesh.getChildren();
  75138. if (children.length !== 0) {
  75139. children.forEach(function (mesh) {
  75140. light.includedOnlyMeshes.push(mesh);
  75141. activateLightOnSubMeshes_1(mesh, light);
  75142. });
  75143. }
  75144. };
  75145. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  75146. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  75147. }
  75148. });
  75149. }
  75150. }
  75151. webVrController_1.attachToPoseControlledCamera(_this);
  75152. // since this is async - sanity check. Is the controller already stored?
  75153. if (_this.controllers.indexOf(webVrController_1) === -1) {
  75154. //add to the controllers array
  75155. _this.controllers.push(webVrController_1);
  75156. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  75157. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  75158. // So we're overriding setting left & right manually to be sure
  75159. var firstViveWandDetected = false;
  75160. for (var i = 0; i < _this.controllers.length; i++) {
  75161. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  75162. if (!firstViveWandDetected) {
  75163. firstViveWandDetected = true;
  75164. _this.controllers[i].hand = "left";
  75165. }
  75166. else {
  75167. _this.controllers[i].hand = "right";
  75168. }
  75169. }
  75170. }
  75171. //did we find enough controllers? Great! let the developer know.
  75172. if (_this.controllers.length >= 2) {
  75173. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  75174. }
  75175. }
  75176. }
  75177. });
  75178. };
  75179. return WebVRFreeCamera;
  75180. }(BABYLON.FreeCamera));
  75181. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  75182. })(BABYLON || (BABYLON = {}));
  75183. //# sourceMappingURL=babylon.webVRCamera.js.map
  75184. var BABYLON;
  75185. (function (BABYLON) {
  75186. // We're mainly based on the logic defined into the FreeCamera code
  75187. /**
  75188. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  75189. * being tilted forward or back and left or right.
  75190. */
  75191. var DeviceOrientationCamera = /** @class */ (function (_super) {
  75192. __extends(DeviceOrientationCamera, _super);
  75193. /**
  75194. * Creates a new device orientation camera. @see DeviceOrientationCamera
  75195. * @param name The name of the camera
  75196. * @param position The start position camera
  75197. * @param scene The scene the camera belongs to
  75198. */
  75199. function DeviceOrientationCamera(name, position, scene) {
  75200. var _this = _super.call(this, name, position, scene) || this;
  75201. _this._quaternionCache = new BABYLON.Quaternion();
  75202. _this.inputs.addDeviceOrientation();
  75203. return _this;
  75204. }
  75205. /**
  75206. * Gets the current instance class name ("DeviceOrientationCamera").
  75207. * This helps avoiding instanceof at run time.
  75208. * @returns the class name
  75209. */
  75210. DeviceOrientationCamera.prototype.getClassName = function () {
  75211. return "DeviceOrientationCamera";
  75212. };
  75213. /**
  75214. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  75215. */
  75216. DeviceOrientationCamera.prototype._checkInputs = function () {
  75217. _super.prototype._checkInputs.call(this);
  75218. this._quaternionCache.copyFrom(this.rotationQuaternion);
  75219. if (this._initialQuaternion) {
  75220. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  75221. }
  75222. };
  75223. /**
  75224. * Reset the camera to its default orientation on the specified axis only.
  75225. * @param axis The axis to reset
  75226. */
  75227. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  75228. var _this = this;
  75229. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  75230. //can only work if this camera has a rotation quaternion already.
  75231. if (!this.rotationQuaternion)
  75232. return;
  75233. if (!this._initialQuaternion) {
  75234. this._initialQuaternion = new BABYLON.Quaternion();
  75235. }
  75236. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  75237. ['x', 'y', 'z'].forEach(function (axisName) {
  75238. if (!axis[axisName]) {
  75239. _this._initialQuaternion[axisName] = 0;
  75240. }
  75241. else {
  75242. _this._initialQuaternion[axisName] *= -1;
  75243. }
  75244. });
  75245. this._initialQuaternion.normalize();
  75246. //force rotation update
  75247. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  75248. };
  75249. return DeviceOrientationCamera;
  75250. }(BABYLON.FreeCamera));
  75251. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  75252. })(BABYLON || (BABYLON = {}));
  75253. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  75254. var BABYLON;
  75255. (function (BABYLON) {
  75256. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  75257. __extends(VRDeviceOrientationFreeCamera, _super);
  75258. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  75259. if (compensateDistortion === void 0) { compensateDistortion = true; }
  75260. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  75261. var _this = _super.call(this, name, position, scene) || this;
  75262. vrCameraMetrics.compensateDistortion = compensateDistortion;
  75263. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  75264. return _this;
  75265. }
  75266. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  75267. return "VRDeviceOrientationFreeCamera";
  75268. };
  75269. return VRDeviceOrientationFreeCamera;
  75270. }(BABYLON.DeviceOrientationCamera));
  75271. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  75272. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  75273. __extends(VRDeviceOrientationGamepadCamera, _super);
  75274. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  75275. if (compensateDistortion === void 0) { compensateDistortion = true; }
  75276. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  75277. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  75278. _this.inputs.addGamepad();
  75279. return _this;
  75280. }
  75281. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  75282. return "VRDeviceOrientationGamepadCamera";
  75283. };
  75284. return VRDeviceOrientationGamepadCamera;
  75285. }(VRDeviceOrientationFreeCamera));
  75286. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  75287. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  75288. __extends(VRDeviceOrientationArcRotateCamera, _super);
  75289. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  75290. if (compensateDistortion === void 0) { compensateDistortion = true; }
  75291. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  75292. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  75293. vrCameraMetrics.compensateDistortion = compensateDistortion;
  75294. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  75295. _this.inputs.addVRDeviceOrientation();
  75296. return _this;
  75297. }
  75298. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  75299. return "VRDeviceOrientationArcRotateCamera";
  75300. };
  75301. return VRDeviceOrientationArcRotateCamera;
  75302. }(BABYLON.ArcRotateCamera));
  75303. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  75304. })(BABYLON || (BABYLON = {}));
  75305. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  75306. var BABYLON;
  75307. (function (BABYLON) {
  75308. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  75309. __extends(AnaglyphFreeCamera, _super);
  75310. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  75311. var _this = _super.call(this, name, position, scene) || this;
  75312. _this.interaxialDistance = interaxialDistance;
  75313. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  75314. return _this;
  75315. }
  75316. AnaglyphFreeCamera.prototype.getClassName = function () {
  75317. return "AnaglyphFreeCamera";
  75318. };
  75319. return AnaglyphFreeCamera;
  75320. }(BABYLON.FreeCamera));
  75321. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  75322. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  75323. __extends(AnaglyphArcRotateCamera, _super);
  75324. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  75325. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  75326. _this.interaxialDistance = interaxialDistance;
  75327. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  75328. return _this;
  75329. }
  75330. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  75331. return "AnaglyphArcRotateCamera";
  75332. };
  75333. return AnaglyphArcRotateCamera;
  75334. }(BABYLON.ArcRotateCamera));
  75335. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  75336. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  75337. __extends(AnaglyphGamepadCamera, _super);
  75338. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  75339. var _this = _super.call(this, name, position, scene) || this;
  75340. _this.interaxialDistance = interaxialDistance;
  75341. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  75342. return _this;
  75343. }
  75344. AnaglyphGamepadCamera.prototype.getClassName = function () {
  75345. return "AnaglyphGamepadCamera";
  75346. };
  75347. return AnaglyphGamepadCamera;
  75348. }(BABYLON.GamepadCamera));
  75349. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  75350. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  75351. __extends(AnaglyphUniversalCamera, _super);
  75352. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  75353. var _this = _super.call(this, name, position, scene) || this;
  75354. _this.interaxialDistance = interaxialDistance;
  75355. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  75356. return _this;
  75357. }
  75358. AnaglyphUniversalCamera.prototype.getClassName = function () {
  75359. return "AnaglyphUniversalCamera";
  75360. };
  75361. return AnaglyphUniversalCamera;
  75362. }(BABYLON.UniversalCamera));
  75363. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  75364. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  75365. __extends(StereoscopicFreeCamera, _super);
  75366. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  75367. var _this = _super.call(this, name, position, scene) || this;
  75368. _this.interaxialDistance = interaxialDistance;
  75369. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  75370. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  75371. return _this;
  75372. }
  75373. StereoscopicFreeCamera.prototype.getClassName = function () {
  75374. return "StereoscopicFreeCamera";
  75375. };
  75376. return StereoscopicFreeCamera;
  75377. }(BABYLON.FreeCamera));
  75378. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  75379. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  75380. __extends(StereoscopicArcRotateCamera, _super);
  75381. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  75382. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  75383. _this.interaxialDistance = interaxialDistance;
  75384. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  75385. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  75386. return _this;
  75387. }
  75388. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  75389. return "StereoscopicArcRotateCamera";
  75390. };
  75391. return StereoscopicArcRotateCamera;
  75392. }(BABYLON.ArcRotateCamera));
  75393. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  75394. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  75395. __extends(StereoscopicGamepadCamera, _super);
  75396. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  75397. var _this = _super.call(this, name, position, scene) || this;
  75398. _this.interaxialDistance = interaxialDistance;
  75399. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  75400. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  75401. return _this;
  75402. }
  75403. StereoscopicGamepadCamera.prototype.getClassName = function () {
  75404. return "StereoscopicGamepadCamera";
  75405. };
  75406. return StereoscopicGamepadCamera;
  75407. }(BABYLON.GamepadCamera));
  75408. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  75409. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  75410. __extends(StereoscopicUniversalCamera, _super);
  75411. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  75412. var _this = _super.call(this, name, position, scene) || this;
  75413. _this.interaxialDistance = interaxialDistance;
  75414. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  75415. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  75416. return _this;
  75417. }
  75418. StereoscopicUniversalCamera.prototype.getClassName = function () {
  75419. return "StereoscopicUniversalCamera";
  75420. };
  75421. return StereoscopicUniversalCamera;
  75422. }(BABYLON.UniversalCamera));
  75423. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  75424. })(BABYLON || (BABYLON = {}));
  75425. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  75426. var BABYLON;
  75427. (function (BABYLON) {
  75428. /**
  75429. * Helps to quickly add VR support to an existing scene.
  75430. * See http://doc.babylonjs.com/how_to/webvr_helper
  75431. */
  75432. var VRExperienceHelper = /** @class */ (function () {
  75433. /**
  75434. * Instantiates a VRExperienceHelper.
  75435. * Helps to quickly add VR support to an existing scene.
  75436. * @param scene The scene the VRExperienceHelper belongs to.
  75437. * @param webVROptions Options to modify the vr experience helper's behavior.
  75438. */
  75439. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  75440. if (webVROptions === void 0) { webVROptions = {}; }
  75441. var _this = this;
  75442. this.webVROptions = webVROptions;
  75443. // Can the system support WebVR, even if a headset isn't plugged in?
  75444. this._webVRsupported = false;
  75445. // If WebVR is supported, is a headset plugged in and are we ready to present?
  75446. this._webVRready = false;
  75447. // Are we waiting for the requestPresent callback to complete?
  75448. this._webVRrequesting = false;
  75449. // Are we presenting to the headset right now?
  75450. this._webVRpresenting = false;
  75451. // Are we presenting in the fullscreen fallback?
  75452. this._fullscreenVRpresenting = false;
  75453. /**
  75454. * Observable raised when entering VR.
  75455. */
  75456. this.onEnteringVRObservable = new BABYLON.Observable();
  75457. /**
  75458. * Observable raised when exiting VR.
  75459. */
  75460. this.onExitingVRObservable = new BABYLON.Observable();
  75461. /**
  75462. * Observable raised when controller mesh is loaded.
  75463. */
  75464. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  75465. this._useCustomVRButton = false;
  75466. this._teleportationRequested = false;
  75467. this._teleportationEnabledOnLeftController = false;
  75468. this._teleportationEnabledOnRightController = false;
  75469. this._interactionsEnabledOnLeftController = false;
  75470. this._interactionsEnabledOnRightController = false;
  75471. this._leftControllerReady = false;
  75472. this._rightControllerReady = false;
  75473. this._floorMeshesCollection = [];
  75474. this._teleportationAllowed = false;
  75475. this._rotationAllowed = true;
  75476. this._teleportationRequestInitiated = false;
  75477. this._teleportationBackRequestInitiated = false;
  75478. this.teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  75479. this._rotationRightAsked = false;
  75480. this._rotationLeftAsked = false;
  75481. this._isDefaultTeleportationTarget = true;
  75482. this._teleportationFillColor = "#444444";
  75483. this._teleportationBorderColor = "#FFFFFF";
  75484. this._rotationAngle = 0;
  75485. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  75486. this._padSensibilityUp = 0.65;
  75487. this._padSensibilityDown = 0.35;
  75488. /**
  75489. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  75490. */
  75491. this.onNewMeshSelected = new BABYLON.Observable();
  75492. /**
  75493. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  75494. */
  75495. this.onNewMeshPicked = new BABYLON.Observable();
  75496. /**
  75497. * Observable raised before camera teleportation
  75498. */
  75499. this.onBeforeCameraTeleport = new BABYLON.Observable();
  75500. /**
  75501. * Observable raised after camera teleportation
  75502. */
  75503. this.onAfterCameraTeleport = new BABYLON.Observable();
  75504. /**
  75505. * Observable raised when current selected mesh gets unselected
  75506. */
  75507. this.onSelectedMeshUnselected = new BABYLON.Observable();
  75508. /**
  75509. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  75510. */
  75511. this.teleportationEnabled = true;
  75512. this._pointerDownOnMeshAsked = false;
  75513. this._isActionableMesh = false;
  75514. this._teleportationInitialized = false;
  75515. this._interactionsEnabled = false;
  75516. this._interactionsRequested = false;
  75517. this._displayGaze = true;
  75518. this._displayLaserPointer = true;
  75519. this._dpadPressed = true;
  75520. this._onResize = function () {
  75521. _this.moveButtonToBottomRight();
  75522. if (_this._fullscreenVRpresenting && _this._webVRready) {
  75523. _this.exitVR();
  75524. }
  75525. };
  75526. this._onFullscreenChange = function () {
  75527. if (document.fullscreen !== undefined) {
  75528. _this._fullscreenVRpresenting = document.fullscreen;
  75529. }
  75530. else if (document.mozFullScreen !== undefined) {
  75531. _this._fullscreenVRpresenting = document.mozFullScreen;
  75532. }
  75533. else if (document.webkitIsFullScreen !== undefined) {
  75534. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  75535. }
  75536. else if (document.msIsFullScreen !== undefined) {
  75537. _this._fullscreenVRpresenting = document.msIsFullScreen;
  75538. }
  75539. if (!_this._fullscreenVRpresenting && _this._canvas) {
  75540. _this.exitVR();
  75541. if (!_this._useCustomVRButton) {
  75542. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  75543. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  75544. }
  75545. }
  75546. };
  75547. this.beforeRender = function () {
  75548. _this._castRayAndSelectObject();
  75549. };
  75550. this._onNewGamepadConnected = function (gamepad) {
  75551. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  75552. if (gamepad.leftStick) {
  75553. gamepad.onleftstickchanged(function (stickValues) {
  75554. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  75555. // Listening to classic/xbox gamepad only if no VR controller is active
  75556. if ((!_this._leftLaserPointer && !_this._rightLaserPointer) ||
  75557. ((_this._leftLaserPointer && !_this._leftLaserPointer.isVisible) &&
  75558. (_this._rightLaserPointer && !_this._rightLaserPointer.isVisible))) {
  75559. _this._checkTeleportWithRay(stickValues);
  75560. _this._checkTeleportBackwards(stickValues);
  75561. }
  75562. }
  75563. });
  75564. }
  75565. if (gamepad.rightStick) {
  75566. gamepad.onrightstickchanged(function (stickValues) {
  75567. if (_this._teleportationInitialized) {
  75568. _this._checkRotate(stickValues);
  75569. }
  75570. });
  75571. }
  75572. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  75573. gamepad.onbuttondown(function (buttonPressed) {
  75574. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  75575. _this._selectionPointerDown();
  75576. }
  75577. });
  75578. gamepad.onbuttonup(function (buttonPressed) {
  75579. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  75580. _this._selectionPointerUp();
  75581. }
  75582. });
  75583. }
  75584. }
  75585. else {
  75586. var webVRController = gamepad;
  75587. _this._tryEnableInteractionOnController(webVRController);
  75588. }
  75589. };
  75590. // This only succeeds if the controller's mesh exists for the controller so this must be called whenever new controller is connected or when mesh is loaded
  75591. this._tryEnableInteractionOnController = function (webVRController) {
  75592. if (webVRController.hand === "left") {
  75593. _this._leftControllerReady = true;
  75594. if (_this._interactionsRequested && !_this._interactionsEnabledOnLeftController) {
  75595. _this._enableInteractionOnController(webVRController);
  75596. }
  75597. if (_this._teleportationRequested && !_this._teleportationEnabledOnLeftController) {
  75598. _this._enableTeleportationOnController(webVRController);
  75599. }
  75600. }
  75601. if (webVRController.hand === "right") {
  75602. _this._rightControllerReady = true;
  75603. if (_this._interactionsRequested && !_this._interactionsEnabledOnRightController) {
  75604. _this._enableInteractionOnController(webVRController);
  75605. }
  75606. if (_this._teleportationRequested && !_this._teleportationEnabledOnRightController) {
  75607. _this._enableTeleportationOnController(webVRController);
  75608. }
  75609. }
  75610. };
  75611. this._onNewGamepadDisconnected = function (gamepad) {
  75612. if (gamepad instanceof BABYLON.WebVRController) {
  75613. if (gamepad.hand === "left") {
  75614. _this._interactionsEnabledOnLeftController = false;
  75615. _this._teleportationEnabledOnLeftController = false;
  75616. _this._leftControllerReady = false;
  75617. if (_this._leftLaserPointer) {
  75618. _this._leftLaserPointer.dispose();
  75619. }
  75620. }
  75621. if (gamepad.hand === "right") {
  75622. _this._interactionsEnabledOnRightController = false;
  75623. _this._teleportationEnabledOnRightController = false;
  75624. _this._rightControllerReady = false;
  75625. if (_this._rightLaserPointer) {
  75626. _this._rightLaserPointer.dispose();
  75627. }
  75628. }
  75629. }
  75630. };
  75631. this._workingVector = BABYLON.Vector3.Zero();
  75632. this._workingQuaternion = BABYLON.Quaternion.Identity();
  75633. this._workingMatrix = BABYLON.Matrix.Identity();
  75634. this._scene = scene;
  75635. this._canvas = scene.getEngine().getRenderingCanvas();
  75636. // Parse options
  75637. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  75638. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  75639. }
  75640. if (webVROptions.createDeviceOrientationCamera === undefined) {
  75641. webVROptions.createDeviceOrientationCamera = true;
  75642. }
  75643. if (webVROptions.defaultHeight === undefined) {
  75644. webVROptions.defaultHeight = 1.7;
  75645. }
  75646. if (webVROptions.useCustomVRButton) {
  75647. this._useCustomVRButton = true;
  75648. if (webVROptions.customVRButton) {
  75649. this._btnVR = webVROptions.customVRButton;
  75650. }
  75651. }
  75652. if (webVROptions.rayLength) {
  75653. this._rayLength = webVROptions.rayLength;
  75654. }
  75655. this._defaultHeight = webVROptions.defaultHeight;
  75656. // Set position
  75657. if (this._scene.activeCamera) {
  75658. this._position = this._scene.activeCamera.position.clone();
  75659. }
  75660. else {
  75661. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  75662. }
  75663. // Set non-vr camera
  75664. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  75665. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  75666. // Copy data from existing camera
  75667. if (this._scene.activeCamera) {
  75668. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  75669. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  75670. // Set rotation from previous camera
  75671. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  75672. var targetCamera = this._scene.activeCamera;
  75673. if (targetCamera.rotationQuaternion) {
  75674. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  75675. }
  75676. else {
  75677. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  75678. }
  75679. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  75680. }
  75681. }
  75682. this._scene.activeCamera = this._deviceOrientationCamera;
  75683. if (this._canvas) {
  75684. this._scene.activeCamera.attachControl(this._canvas);
  75685. }
  75686. }
  75687. else {
  75688. this._existingCamera = this._scene.activeCamera;
  75689. }
  75690. // Create VR cameras
  75691. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  75692. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  75693. }
  75694. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  75695. this._webVRCamera.useStandingMatrix();
  75696. // Create default button
  75697. if (!this._useCustomVRButton) {
  75698. this._btnVR = document.createElement("BUTTON");
  75699. this._btnVR.className = "babylonVRicon";
  75700. this._btnVR.id = "babylonVRiconbtn";
  75701. this._btnVR.title = "Click to switch to VR";
  75702. 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) }";
  75703. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  75704. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  75705. // css += ".babylonVRicon.vrdisplaysupported { }";
  75706. // css += ".babylonVRicon.vrdisplayready { }";
  75707. // css += ".babylonVRicon.vrdisplayrequesting { }";
  75708. var style = document.createElement('style');
  75709. style.appendChild(document.createTextNode(css));
  75710. document.getElementsByTagName('head')[0].appendChild(style);
  75711. this.moveButtonToBottomRight();
  75712. }
  75713. // VR button click event
  75714. if (this._btnVR) {
  75715. this._btnVR.addEventListener("click", function () {
  75716. if (!_this.isInVRMode) {
  75717. _this.enterVR();
  75718. }
  75719. else {
  75720. _this.exitVR();
  75721. }
  75722. });
  75723. }
  75724. // Window events
  75725. window.addEventListener("resize", this._onResize);
  75726. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  75727. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  75728. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  75729. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  75730. // Display vr button when headset is connected
  75731. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  75732. this.displayVRButton();
  75733. }
  75734. else {
  75735. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  75736. if (e.vrDisplay) {
  75737. _this.displayVRButton();
  75738. }
  75739. });
  75740. }
  75741. // Exiting VR mode using 'ESC' key on desktop
  75742. this._onKeyDown = function (event) {
  75743. if (event.keyCode === 27 && _this.isInVRMode) {
  75744. _this.exitVR();
  75745. }
  75746. };
  75747. document.addEventListener("keydown", this._onKeyDown);
  75748. // Exiting VR mode double tapping the touch screen
  75749. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  75750. if (_this.isInVRMode) {
  75751. _this.exitVR();
  75752. if (_this._fullscreenVRpresenting) {
  75753. _this._scene.getEngine().switchFullscreen(true);
  75754. }
  75755. }
  75756. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  75757. // Listen for WebVR display changes
  75758. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  75759. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  75760. this._onVRRequestPresentStart = function () {
  75761. _this._webVRrequesting = true;
  75762. _this.updateButtonVisibility();
  75763. };
  75764. this._onVRRequestPresentComplete = function (success) {
  75765. _this._webVRrequesting = false;
  75766. _this.updateButtonVisibility();
  75767. };
  75768. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  75769. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  75770. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  75771. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  75772. scene.onDisposeObservable.add(function () {
  75773. _this.dispose();
  75774. });
  75775. // Gamepad connection events
  75776. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  75777. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  75778. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  75779. this.updateButtonVisibility();
  75780. //create easing functions
  75781. this._circleEase = new BABYLON.CircleEase();
  75782. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  75783. }
  75784. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  75785. /** Return this.onEnteringVRObservable
  75786. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  75787. */
  75788. get: function () {
  75789. return this.onEnteringVRObservable;
  75790. },
  75791. enumerable: true,
  75792. configurable: true
  75793. });
  75794. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  75795. /** Return this.onExitingVRObservable
  75796. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  75797. */
  75798. get: function () {
  75799. return this.onExitingVRObservable;
  75800. },
  75801. enumerable: true,
  75802. configurable: true
  75803. });
  75804. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  75805. /** Return this.onControllerMeshLoadedObservable
  75806. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  75807. */
  75808. get: function () {
  75809. return this.onControllerMeshLoadedObservable;
  75810. },
  75811. enumerable: true,
  75812. configurable: true
  75813. });
  75814. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  75815. /**
  75816. * The mesh used to display where the user is going to teleport.
  75817. */
  75818. get: function () {
  75819. return this._teleportationTarget;
  75820. },
  75821. /**
  75822. * Sets the mesh to be used to display where the user is going to teleport.
  75823. */
  75824. set: function (value) {
  75825. if (value) {
  75826. value.name = "teleportationTarget";
  75827. this._isDefaultTeleportationTarget = false;
  75828. this._teleportationTarget = value;
  75829. }
  75830. },
  75831. enumerable: true,
  75832. configurable: true
  75833. });
  75834. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  75835. /**
  75836. * If the ray of the gaze should be displayed.
  75837. */
  75838. get: function () {
  75839. return this._displayGaze;
  75840. },
  75841. /**
  75842. * Sets if the ray of the gaze should be displayed.
  75843. */
  75844. set: function (value) {
  75845. this._displayGaze = value;
  75846. if (!value) {
  75847. this._gazeTracker.isVisible = false;
  75848. }
  75849. },
  75850. enumerable: true,
  75851. configurable: true
  75852. });
  75853. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  75854. /**
  75855. * If the ray of the LaserPointer should be displayed.
  75856. */
  75857. get: function () {
  75858. return this._displayLaserPointer;
  75859. },
  75860. /**
  75861. * Sets if the ray of the LaserPointer should be displayed.
  75862. */
  75863. set: function (value) {
  75864. this._displayLaserPointer = value;
  75865. if (!value) {
  75866. if (this._rightLaserPointer) {
  75867. this._rightLaserPointer.isVisible = false;
  75868. }
  75869. if (this._leftLaserPointer) {
  75870. this._leftLaserPointer.isVisible = false;
  75871. }
  75872. }
  75873. else {
  75874. if (this._rightLaserPointer) {
  75875. this._rightLaserPointer.isVisible = true;
  75876. }
  75877. else if (this._leftLaserPointer) {
  75878. this._leftLaserPointer.isVisible = true;
  75879. }
  75880. }
  75881. },
  75882. enumerable: true,
  75883. configurable: true
  75884. });
  75885. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  75886. /**
  75887. * The deviceOrientationCamera used as the camera when not in VR.
  75888. */
  75889. get: function () {
  75890. return this._deviceOrientationCamera;
  75891. },
  75892. enumerable: true,
  75893. configurable: true
  75894. });
  75895. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  75896. /**
  75897. * Based on the current WebVR support, returns the current VR camera used.
  75898. */
  75899. get: function () {
  75900. if (this._webVRready) {
  75901. return this._webVRCamera;
  75902. }
  75903. else {
  75904. return this._scene.activeCamera;
  75905. }
  75906. },
  75907. enumerable: true,
  75908. configurable: true
  75909. });
  75910. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  75911. /**
  75912. * The webVRCamera which is used when in VR.
  75913. */
  75914. get: function () {
  75915. return this._webVRCamera;
  75916. },
  75917. enumerable: true,
  75918. configurable: true
  75919. });
  75920. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  75921. /**
  75922. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  75923. */
  75924. get: function () {
  75925. return this._vrDeviceOrientationCamera;
  75926. },
  75927. enumerable: true,
  75928. configurable: true
  75929. });
  75930. // Raised when one of the controller has loaded successfully its associated default mesh
  75931. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  75932. this._tryEnableInteractionOnController(webVRController);
  75933. try {
  75934. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  75935. }
  75936. catch (err) {
  75937. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  75938. }
  75939. };
  75940. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  75941. /**
  75942. * Gets a value indicating if we are currently in VR mode.
  75943. */
  75944. get: function () {
  75945. return this._webVRpresenting || this._fullscreenVRpresenting;
  75946. },
  75947. enumerable: true,
  75948. configurable: true
  75949. });
  75950. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  75951. var vrDisplay = this._scene.getEngine().getVRDevice();
  75952. if (vrDisplay) {
  75953. var wasPresenting = this._webVRpresenting;
  75954. // A VR display is connected
  75955. this._webVRpresenting = vrDisplay.isPresenting;
  75956. if (wasPresenting && !this._webVRpresenting)
  75957. this.exitVR();
  75958. }
  75959. else {
  75960. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  75961. }
  75962. this.updateButtonVisibility();
  75963. };
  75964. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  75965. this._webVRsupported = eventArgs.vrSupported;
  75966. this._webVRready = !!eventArgs.vrDisplay;
  75967. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  75968. this.updateButtonVisibility();
  75969. };
  75970. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  75971. if (this._canvas && !this._useCustomVRButton) {
  75972. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  75973. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  75974. }
  75975. };
  75976. VRExperienceHelper.prototype.displayVRButton = function () {
  75977. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  75978. document.body.appendChild(this._btnVR);
  75979. this._btnVRDisplayed = true;
  75980. }
  75981. };
  75982. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  75983. if (!this._btnVR || this._useCustomVRButton) {
  75984. return;
  75985. }
  75986. this._btnVR.className = "babylonVRicon";
  75987. if (this.isInVRMode) {
  75988. this._btnVR.className += " vrdisplaypresenting";
  75989. }
  75990. else {
  75991. if (this._webVRready)
  75992. this._btnVR.className += " vrdisplayready";
  75993. if (this._webVRsupported)
  75994. this._btnVR.className += " vrdisplaysupported";
  75995. if (this._webVRrequesting)
  75996. this._btnVR.className += " vrdisplayrequesting";
  75997. }
  75998. };
  75999. /**
  76000. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  76001. * Otherwise, will use the fullscreen API.
  76002. */
  76003. VRExperienceHelper.prototype.enterVR = function () {
  76004. if (this.onEnteringVRObservable) {
  76005. try {
  76006. this.onEnteringVRObservable.notifyObservers(this);
  76007. }
  76008. catch (err) {
  76009. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  76010. }
  76011. }
  76012. if (this._scene.activeCamera) {
  76013. this._position = this._scene.activeCamera.position.clone();
  76014. // make sure that we return to the last active camera
  76015. this._existingCamera = this._scene.activeCamera;
  76016. }
  76017. if (this._webVRrequesting)
  76018. return;
  76019. // If WebVR is supported and a headset is connected
  76020. if (this._webVRready) {
  76021. if (!this._webVRpresenting) {
  76022. this._webVRCamera.position = this._position;
  76023. this._scene.activeCamera = this._webVRCamera;
  76024. }
  76025. }
  76026. else if (this._vrDeviceOrientationCamera) {
  76027. this._vrDeviceOrientationCamera.position = this._position;
  76028. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  76029. this._scene.getEngine().switchFullscreen(true);
  76030. this.updateButtonVisibility();
  76031. }
  76032. if (this._scene.activeCamera && this._canvas) {
  76033. this._scene.activeCamera.attachControl(this._canvas);
  76034. }
  76035. if (this._interactionsEnabled) {
  76036. this._scene.registerBeforeRender(this.beforeRender);
  76037. }
  76038. };
  76039. /**
  76040. * Attempt to exit VR, or fullscreen.
  76041. */
  76042. VRExperienceHelper.prototype.exitVR = function () {
  76043. if (this.onExitingVRObservable) {
  76044. try {
  76045. this.onExitingVRObservable.notifyObservers(this);
  76046. }
  76047. catch (err) {
  76048. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  76049. }
  76050. }
  76051. if (this._webVRpresenting) {
  76052. this._scene.getEngine().disableVR();
  76053. }
  76054. if (this._scene.activeCamera) {
  76055. this._position = this._scene.activeCamera.position.clone();
  76056. }
  76057. if (this._deviceOrientationCamera) {
  76058. this._deviceOrientationCamera.position = this._position;
  76059. this._scene.activeCamera = this._deviceOrientationCamera;
  76060. if (this._canvas) {
  76061. this._scene.activeCamera.attachControl(this._canvas);
  76062. }
  76063. }
  76064. else if (this._existingCamera) {
  76065. this._existingCamera.position = this._position;
  76066. this._scene.activeCamera = this._existingCamera;
  76067. }
  76068. this.updateButtonVisibility();
  76069. if (this._interactionsEnabled) {
  76070. this._scene.unregisterBeforeRender(this.beforeRender);
  76071. }
  76072. };
  76073. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  76074. /**
  76075. * The position of the vr experience helper.
  76076. */
  76077. get: function () {
  76078. return this._position;
  76079. },
  76080. /**
  76081. * Sets the position of the vr experience helper.
  76082. */
  76083. set: function (value) {
  76084. this._position = value;
  76085. if (this._scene.activeCamera) {
  76086. this._scene.activeCamera.position = value;
  76087. }
  76088. },
  76089. enumerable: true,
  76090. configurable: true
  76091. });
  76092. /**
  76093. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  76094. */
  76095. VRExperienceHelper.prototype.enableInteractions = function () {
  76096. var _this = this;
  76097. if (!this._interactionsEnabled) {
  76098. this._interactionsRequested = true;
  76099. if (this._leftControllerReady && this._webVRCamera.leftController) {
  76100. this._enableInteractionOnController(this._webVRCamera.leftController);
  76101. }
  76102. if (this._rightControllerReady && this._webVRCamera.rightController) {
  76103. this._enableInteractionOnController(this._webVRCamera.rightController);
  76104. }
  76105. this._createGazeTracker();
  76106. this.raySelectionPredicate = function (mesh) {
  76107. return mesh.isVisible;
  76108. };
  76109. this.meshSelectionPredicate = function (mesh) {
  76110. return true;
  76111. };
  76112. this._raySelectionPredicate = function (mesh) {
  76113. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  76114. && mesh.name.indexOf("teleportationTarget") === -1
  76115. && mesh.name.indexOf("torusTeleportation") === -1
  76116. && mesh.name.indexOf("laserPointer") === -1)) {
  76117. return _this.raySelectionPredicate(mesh);
  76118. }
  76119. return false;
  76120. };
  76121. this._interactionsEnabled = true;
  76122. }
  76123. };
  76124. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  76125. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  76126. if (this._floorMeshesCollection[i].id === mesh.id) {
  76127. return true;
  76128. }
  76129. }
  76130. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  76131. return true;
  76132. }
  76133. return false;
  76134. };
  76135. /**
  76136. * Adds a floor mesh to be used for teleportation.
  76137. * @param floorMesh the mesh to be used for teleportation.
  76138. */
  76139. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  76140. if (!this._floorMeshesCollection) {
  76141. return;
  76142. }
  76143. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  76144. return;
  76145. }
  76146. this._floorMeshesCollection.push(floorMesh);
  76147. };
  76148. /**
  76149. * Removes a floor mesh from being used for teleportation.
  76150. * @param floorMesh the mesh to be removed.
  76151. */
  76152. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  76153. if (!this._floorMeshesCollection) {
  76154. return;
  76155. }
  76156. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  76157. if (meshIndex !== -1) {
  76158. this._floorMeshesCollection.splice(meshIndex, 1);
  76159. }
  76160. };
  76161. /**
  76162. * Enables interactions and teleportation using the VR controllers and gaze.
  76163. * @param vrTeleportationOptions options to modify teleportation behavior.
  76164. */
  76165. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  76166. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  76167. if (!this._teleportationInitialized) {
  76168. this._teleportationRequested = true;
  76169. this.enableInteractions();
  76170. if (vrTeleportationOptions.floorMeshName) {
  76171. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  76172. }
  76173. if (vrTeleportationOptions.floorMeshes) {
  76174. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  76175. }
  76176. if (this._leftControllerReady && this._webVRCamera.leftController) {
  76177. this._enableTeleportationOnController(this._webVRCamera.leftController);
  76178. }
  76179. if (this._rightControllerReady && this._webVRCamera.rightController) {
  76180. this._enableTeleportationOnController(this._webVRCamera.rightController);
  76181. }
  76182. // Creates an image processing post process for the vignette not relying
  76183. // on the main scene configuration for image processing to reduce setup and spaces
  76184. // (gamma/linear) conflicts.
  76185. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  76186. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  76187. imageProcessingConfiguration.vignetteEnabled = true;
  76188. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  76189. this._webVRCamera.detachPostProcess(this._postProcessMove);
  76190. this._passProcessMove = new BABYLON.PassPostProcess("pass", 1.0, this._webVRCamera);
  76191. this._teleportationInitialized = true;
  76192. if (this._isDefaultTeleportationTarget) {
  76193. this._createTeleportationCircles();
  76194. }
  76195. }
  76196. };
  76197. VRExperienceHelper.prototype._enableInteractionOnController = function (webVRController) {
  76198. var _this = this;
  76199. var controllerMesh = webVRController.mesh;
  76200. if (controllerMesh) {
  76201. var makeNotPick = function (root) {
  76202. root.name += " laserPointer";
  76203. root.getChildMeshes().forEach(function (c) {
  76204. makeNotPick(c);
  76205. });
  76206. };
  76207. makeNotPick(controllerMesh);
  76208. var childMeshes = controllerMesh.getChildMeshes();
  76209. for (var i = 0; i < childMeshes.length; i++) {
  76210. if (childMeshes[i].name && childMeshes[i].name.indexOf("POINTING_POSE") >= 0) {
  76211. controllerMesh = childMeshes[i];
  76212. break;
  76213. }
  76214. }
  76215. var laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, this._scene, false);
  76216. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", this._scene);
  76217. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  76218. laserPointerMaterial.alpha = 0.6;
  76219. laserPointer.material = laserPointerMaterial;
  76220. laserPointer.rotation.x = Math.PI / 2;
  76221. laserPointer.parent = controllerMesh;
  76222. laserPointer.position.z = -0.5;
  76223. laserPointer.isVisible = false;
  76224. if (webVRController.hand === "left") {
  76225. this._leftLaserPointer = laserPointer;
  76226. this._interactionsEnabledOnLeftController = true;
  76227. if (!this._rightLaserPointer) {
  76228. this._leftLaserPointer.isVisible = true;
  76229. }
  76230. }
  76231. else {
  76232. this._rightLaserPointer = laserPointer;
  76233. this._interactionsEnabledOnRightController = true;
  76234. if (!this._leftLaserPointer) {
  76235. this._rightLaserPointer.isVisible = true;
  76236. }
  76237. }
  76238. webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  76239. // Enabling / disabling laserPointer
  76240. if (_this._displayLaserPointer && stateObject.value === 1) {
  76241. laserPointer.isVisible = !laserPointer.isVisible;
  76242. // Laser pointer can only be active on left or right, not both at the same time
  76243. if (webVRController.hand === "left" && _this._rightLaserPointer) {
  76244. _this._rightLaserPointer.isVisible = false;
  76245. }
  76246. else if (_this._leftLaserPointer) {
  76247. _this._leftLaserPointer.isVisible = false;
  76248. }
  76249. }
  76250. });
  76251. webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  76252. if (!_this._pointerDownOnMeshAsked) {
  76253. if (stateObject.value > _this._padSensibilityUp) {
  76254. _this._selectionPointerDown();
  76255. }
  76256. }
  76257. else if (stateObject.value < _this._padSensibilityDown) {
  76258. _this._selectionPointerUp();
  76259. }
  76260. });
  76261. }
  76262. };
  76263. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, webVRController) {
  76264. if (webVRController === void 0) { webVRController = null; }
  76265. if (!this._teleportationRequestInitiated) {
  76266. if (stateObject.y < -this._padSensibilityUp && this._dpadPressed) {
  76267. if (webVRController) {
  76268. // If laser pointer wasn't enabled yet
  76269. if (this._displayLaserPointer && webVRController.hand === "left" && this._leftLaserPointer) {
  76270. this._leftLaserPointer.isVisible = true;
  76271. if (this._rightLaserPointer) {
  76272. this._rightLaserPointer.isVisible = false;
  76273. }
  76274. }
  76275. else if (this._displayLaserPointer && this._rightLaserPointer) {
  76276. this._rightLaserPointer.isVisible = true;
  76277. if (this._leftLaserPointer) {
  76278. this._leftLaserPointer.isVisible = false;
  76279. }
  76280. }
  76281. }
  76282. this._teleportationRequestInitiated = true;
  76283. }
  76284. }
  76285. else {
  76286. // Listening to the proper controller values changes to confirm teleportation
  76287. if (webVRController == null
  76288. || (webVRController.hand === "left" && this._leftLaserPointer && this._leftLaserPointer.isVisible)
  76289. || (webVRController.hand === "right" && this._rightLaserPointer && this._rightLaserPointer.isVisible)) {
  76290. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  76291. if (this._teleportationAllowed) {
  76292. this._teleportationAllowed = false;
  76293. this._teleportCamera();
  76294. }
  76295. this._teleportationRequestInitiated = false;
  76296. }
  76297. }
  76298. }
  76299. };
  76300. VRExperienceHelper.prototype._selectionPointerDown = function () {
  76301. this._pointerDownOnMeshAsked = true;
  76302. if (this._currentMeshSelected && this._currentHit) {
  76303. this._scene.simulatePointerDown(this._currentHit);
  76304. }
  76305. };
  76306. VRExperienceHelper.prototype._selectionPointerUp = function () {
  76307. if (this._currentMeshSelected && this._currentHit) {
  76308. this._scene.simulatePointerUp(this._currentHit);
  76309. }
  76310. this._pointerDownOnMeshAsked = false;
  76311. };
  76312. VRExperienceHelper.prototype._checkRotate = function (stateObject) {
  76313. // Only rotate when user is not currently selecting a teleportation location
  76314. if (this._teleportationRequestInitiated) {
  76315. return;
  76316. }
  76317. if (!this._rotationLeftAsked) {
  76318. if (stateObject.x < -this._padSensibilityUp && this._dpadPressed) {
  76319. this._rotationLeftAsked = true;
  76320. if (this._rotationAllowed) {
  76321. this._rotateCamera(false);
  76322. }
  76323. }
  76324. }
  76325. else {
  76326. if (stateObject.x > -this._padSensibilityDown) {
  76327. this._rotationLeftAsked = false;
  76328. }
  76329. }
  76330. if (!this._rotationRightAsked) {
  76331. if (stateObject.x > this._padSensibilityUp && this._dpadPressed) {
  76332. this._rotationRightAsked = true;
  76333. if (this._rotationAllowed) {
  76334. this._rotateCamera(true);
  76335. }
  76336. }
  76337. }
  76338. else {
  76339. if (stateObject.x < this._padSensibilityDown) {
  76340. this._rotationRightAsked = false;
  76341. }
  76342. }
  76343. };
  76344. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject) {
  76345. // Only teleport backwards when user is not currently selecting a teleportation location
  76346. if (this._teleportationRequestInitiated) {
  76347. return;
  76348. }
  76349. // Teleport backwards
  76350. if (stateObject.y > this._padSensibilityUp && this._dpadPressed) {
  76351. if (!this._teleportationBackRequestInitiated) {
  76352. if (!this.currentVRCamera) {
  76353. return;
  76354. }
  76355. // Get rotation and position of the current camera
  76356. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  76357. var position = this.currentVRCamera.position;
  76358. // If the camera has device position, use that instead
  76359. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  76360. rotation = this.currentVRCamera.deviceRotationQuaternion;
  76361. position = this.currentVRCamera.devicePosition;
  76362. }
  76363. // Get matrix with only the y rotation of the device rotation
  76364. rotation.toEulerAnglesToRef(this._workingVector);
  76365. this._workingVector.z = 0;
  76366. this._workingVector.x = 0;
  76367. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  76368. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  76369. // Rotate backwards ray by device rotation to cast at the ground behind the user
  76370. BABYLON.Vector3.TransformCoordinatesToRef(this.teleportBackwardsVector, this._workingMatrix, this._workingVector);
  76371. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  76372. var ray = new BABYLON.Ray(position, this._workingVector);
  76373. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  76374. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  76375. this._teleportCamera(hit.pickedPoint);
  76376. }
  76377. this._teleportationBackRequestInitiated = true;
  76378. }
  76379. }
  76380. else {
  76381. this._teleportationBackRequestInitiated = false;
  76382. }
  76383. };
  76384. VRExperienceHelper.prototype._enableTeleportationOnController = function (webVRController) {
  76385. var _this = this;
  76386. var controllerMesh = webVRController.mesh;
  76387. if (controllerMesh) {
  76388. if (webVRController.hand === "left") {
  76389. if (!this._interactionsEnabledOnLeftController) {
  76390. this._enableInteractionOnController(webVRController);
  76391. }
  76392. this._teleportationEnabledOnLeftController = true;
  76393. }
  76394. else {
  76395. if (!this._interactionsEnabledOnRightController) {
  76396. this._enableInteractionOnController(webVRController);
  76397. }
  76398. this._teleportationEnabledOnRightController = true;
  76399. }
  76400. if (webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  76401. this._dpadPressed = false;
  76402. webVRController.onPadStateChangedObservable.add(function (stateObject) {
  76403. _this._dpadPressed = stateObject.pressed;
  76404. if (!_this._dpadPressed) {
  76405. _this._rotationLeftAsked = false;
  76406. _this._rotationRightAsked = false;
  76407. _this._teleportationBackRequestInitiated = false;
  76408. }
  76409. });
  76410. }
  76411. webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  76412. if (_this.teleportationEnabled) {
  76413. _this._checkTeleportBackwards(stateObject);
  76414. _this._checkTeleportWithRay(stateObject, webVRController);
  76415. }
  76416. _this._checkRotate(stateObject);
  76417. });
  76418. }
  76419. };
  76420. // Gaze support used to point to teleport or to interact with an object
  76421. VRExperienceHelper.prototype._createGazeTracker = function () {
  76422. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, this._scene, false);
  76423. this._gazeTracker.bakeCurrentTransformIntoVertices();
  76424. this._gazeTracker.isPickable = false;
  76425. this._gazeTracker.isVisible = false;
  76426. var targetMat = new BABYLON.StandardMaterial("targetMat", this._scene);
  76427. targetMat.specularColor = BABYLON.Color3.Black();
  76428. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  76429. targetMat.backFaceCulling = false;
  76430. this._gazeTracker.material = targetMat;
  76431. };
  76432. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  76433. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  76434. this._teleportationTarget.isPickable = false;
  76435. var length = 512;
  76436. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  76437. dynamicTexture.hasAlpha = true;
  76438. var context = dynamicTexture.getContext();
  76439. var centerX = length / 2;
  76440. var centerY = length / 2;
  76441. var radius = 200;
  76442. context.beginPath();
  76443. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  76444. context.fillStyle = this._teleportationFillColor;
  76445. context.fill();
  76446. context.lineWidth = 10;
  76447. context.strokeStyle = this._teleportationBorderColor;
  76448. context.stroke();
  76449. context.closePath();
  76450. dynamicTexture.update();
  76451. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  76452. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  76453. this._teleportationTarget.material = teleportationCircleMaterial;
  76454. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  76455. torus.isPickable = false;
  76456. torus.parent = this._teleportationTarget;
  76457. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  76458. var keys = [];
  76459. keys.push({
  76460. frame: 0,
  76461. value: 0
  76462. });
  76463. keys.push({
  76464. frame: 30,
  76465. value: 0.4
  76466. });
  76467. keys.push({
  76468. frame: 60,
  76469. value: 0
  76470. });
  76471. animationInnerCircle.setKeys(keys);
  76472. var easingFunction = new BABYLON.SineEase();
  76473. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  76474. animationInnerCircle.setEasingFunction(easingFunction);
  76475. torus.animations = [];
  76476. torus.animations.push(animationInnerCircle);
  76477. this._scene.beginAnimation(torus, 0, 60, true);
  76478. this._hideTeleportationTarget();
  76479. };
  76480. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  76481. if (this._teleportationInitialized) {
  76482. this._teleportationTarget.isVisible = true;
  76483. if (this._isDefaultTeleportationTarget) {
  76484. this._teleportationTarget.getChildren()[0].isVisible = true;
  76485. }
  76486. }
  76487. };
  76488. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  76489. if (this._teleportationInitialized) {
  76490. this._teleportationTarget.isVisible = false;
  76491. if (this._isDefaultTeleportationTarget) {
  76492. this._teleportationTarget.getChildren()[0].isVisible = false;
  76493. }
  76494. }
  76495. };
  76496. VRExperienceHelper.prototype._rotateCamera = function (right) {
  76497. var _this = this;
  76498. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  76499. return;
  76500. }
  76501. if (right) {
  76502. this._rotationAngle++;
  76503. }
  76504. else {
  76505. this._rotationAngle--;
  76506. }
  76507. this.currentVRCamera.animations = [];
  76508. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  76509. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  76510. var animationRotationKeys = [];
  76511. animationRotationKeys.push({
  76512. frame: 0,
  76513. value: this.currentVRCamera.rotationQuaternion
  76514. });
  76515. animationRotationKeys.push({
  76516. frame: 6,
  76517. value: target
  76518. });
  76519. animationRotation.setKeys(animationRotationKeys);
  76520. animationRotation.setEasingFunction(this._circleEase);
  76521. this.currentVRCamera.animations.push(animationRotation);
  76522. this._postProcessMove.animations = [];
  76523. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  76524. var vignetteWeightKeys = [];
  76525. vignetteWeightKeys.push({
  76526. frame: 0,
  76527. value: 0
  76528. });
  76529. vignetteWeightKeys.push({
  76530. frame: 3,
  76531. value: 4
  76532. });
  76533. vignetteWeightKeys.push({
  76534. frame: 6,
  76535. value: 0
  76536. });
  76537. animationPP.setKeys(vignetteWeightKeys);
  76538. animationPP.setEasingFunction(this._circleEase);
  76539. this._postProcessMove.animations.push(animationPP);
  76540. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  76541. var vignetteStretchKeys = [];
  76542. vignetteStretchKeys.push({
  76543. frame: 0,
  76544. value: 0
  76545. });
  76546. vignetteStretchKeys.push({
  76547. frame: 3,
  76548. value: 10
  76549. });
  76550. vignetteStretchKeys.push({
  76551. frame: 6,
  76552. value: 0
  76553. });
  76554. animationPP2.setKeys(vignetteStretchKeys);
  76555. animationPP2.setEasingFunction(this._circleEase);
  76556. this._postProcessMove.animations.push(animationPP2);
  76557. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  76558. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  76559. this._webVRCamera.attachPostProcess(this._postProcessMove);
  76560. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  76561. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  76562. });
  76563. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  76564. };
  76565. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit) {
  76566. if (hit.pickedPoint) {
  76567. this._teleportationAllowed = true;
  76568. if (this._teleportationRequestInitiated) {
  76569. this._displayTeleportationTarget();
  76570. }
  76571. else {
  76572. this._hideTeleportationTarget();
  76573. }
  76574. this._haloCenter.copyFrom(hit.pickedPoint);
  76575. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  76576. var pickNormal = hit.getNormal(true, false);
  76577. if (pickNormal) {
  76578. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  76579. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  76580. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  76581. }
  76582. this._teleportationTarget.position.y += 0.1;
  76583. }
  76584. };
  76585. VRExperienceHelper.prototype._teleportCamera = function (location) {
  76586. var _this = this;
  76587. if (location === void 0) { location = null; }
  76588. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  76589. return;
  76590. }
  76591. if (!location) {
  76592. location = this._haloCenter;
  76593. }
  76594. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  76595. // offset of the headset from the anchor.
  76596. if (this.webVRCamera.leftCamera) {
  76597. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  76598. this._workingVector.subtractInPlace(this.webVRCamera.position);
  76599. location.subtractToRef(this._workingVector, this._workingVector);
  76600. }
  76601. else {
  76602. this._workingVector.copyFrom(location);
  76603. }
  76604. // Add height to account for user's height offset
  76605. if (this.isInVRMode) {
  76606. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround();
  76607. }
  76608. else {
  76609. this._workingVector.y += this._defaultHeight;
  76610. }
  76611. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  76612. // Create animation from the camera's position to the new location
  76613. this.currentVRCamera.animations = [];
  76614. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  76615. var animationCameraTeleportationKeys = [{
  76616. frame: 0,
  76617. value: this.currentVRCamera.position
  76618. },
  76619. {
  76620. frame: 11,
  76621. value: this._workingVector
  76622. }
  76623. ];
  76624. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  76625. animationCameraTeleportation.setEasingFunction(this._circleEase);
  76626. this.currentVRCamera.animations.push(animationCameraTeleportation);
  76627. this._postProcessMove.animations = [];
  76628. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  76629. var vignetteWeightKeys = [];
  76630. vignetteWeightKeys.push({
  76631. frame: 0,
  76632. value: 0
  76633. });
  76634. vignetteWeightKeys.push({
  76635. frame: 5,
  76636. value: 8
  76637. });
  76638. vignetteWeightKeys.push({
  76639. frame: 11,
  76640. value: 0
  76641. });
  76642. animationPP.setKeys(vignetteWeightKeys);
  76643. this._postProcessMove.animations.push(animationPP);
  76644. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  76645. var vignetteStretchKeys = [];
  76646. vignetteStretchKeys.push({
  76647. frame: 0,
  76648. value: 0
  76649. });
  76650. vignetteStretchKeys.push({
  76651. frame: 5,
  76652. value: 10
  76653. });
  76654. vignetteStretchKeys.push({
  76655. frame: 11,
  76656. value: 0
  76657. });
  76658. animationPP2.setKeys(vignetteStretchKeys);
  76659. this._postProcessMove.animations.push(animationPP2);
  76660. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  76661. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  76662. this._webVRCamera.attachPostProcess(this._postProcessMove);
  76663. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  76664. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  76665. });
  76666. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  76667. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  76668. });
  76669. };
  76670. VRExperienceHelper.prototype._castRayAndSelectObject = function () {
  76671. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  76672. return;
  76673. }
  76674. var ray;
  76675. if (this._leftLaserPointer && this._leftLaserPointer.isVisible && this.currentVRCamera.leftController) {
  76676. ray = this.currentVRCamera.leftController.getForwardRay(this._rayLength);
  76677. }
  76678. else if (this._rightLaserPointer && this._rightLaserPointer.isVisible && this.currentVRCamera.rightController) {
  76679. ray = this.currentVRCamera.rightController.getForwardRay(this._rayLength);
  76680. }
  76681. else {
  76682. ray = this.currentVRCamera.getForwardRay(this._rayLength);
  76683. }
  76684. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  76685. // Moving the gazeTracker on the mesh face targetted
  76686. if (hit && hit.pickedPoint) {
  76687. if (this._displayGaze) {
  76688. var multiplier = 1;
  76689. this._gazeTracker.isVisible = true;
  76690. if (this._isActionableMesh) {
  76691. multiplier = 3;
  76692. }
  76693. this._gazeTracker.scaling.x = hit.distance * multiplier;
  76694. this._gazeTracker.scaling.y = hit.distance * multiplier;
  76695. this._gazeTracker.scaling.z = hit.distance * multiplier;
  76696. var pickNormal = hit.getNormal();
  76697. // To avoid z-fighting
  76698. var deltaFighting = 0.002;
  76699. if (pickNormal) {
  76700. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  76701. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  76702. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._gazeTracker.rotation);
  76703. }
  76704. this._gazeTracker.position.copyFrom(hit.pickedPoint);
  76705. if (this._gazeTracker.position.x < 0) {
  76706. this._gazeTracker.position.x += deltaFighting;
  76707. }
  76708. else {
  76709. this._gazeTracker.position.x -= deltaFighting;
  76710. }
  76711. if (this._gazeTracker.position.y < 0) {
  76712. this._gazeTracker.position.y += deltaFighting;
  76713. }
  76714. else {
  76715. this._gazeTracker.position.y -= deltaFighting;
  76716. }
  76717. if (this._gazeTracker.position.z < 0) {
  76718. this._gazeTracker.position.z += deltaFighting;
  76719. }
  76720. else {
  76721. this._gazeTracker.position.z -= deltaFighting;
  76722. }
  76723. }
  76724. // Changing the size of the laser pointer based on the distance from the targetted point
  76725. if (this._rightLaserPointer && this._rightLaserPointer.isVisible) {
  76726. this._rightLaserPointer.scaling.y = hit.distance;
  76727. this._rightLaserPointer.position.z = -hit.distance / 2;
  76728. }
  76729. if (this._leftLaserPointer && this._leftLaserPointer.isVisible) {
  76730. this._leftLaserPointer.scaling.y = hit.distance;
  76731. this._leftLaserPointer.position.z = -hit.distance / 2;
  76732. }
  76733. }
  76734. else {
  76735. this._gazeTracker.isVisible = false;
  76736. }
  76737. if (hit && hit.pickedMesh) {
  76738. this._currentHit = hit;
  76739. if (this._pointerDownOnMeshAsked) {
  76740. this._scene.simulatePointerMove(this._currentHit);
  76741. }
  76742. // The object selected is the floor, we're in a teleportation scenario
  76743. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  76744. // Moving the teleportation area to this targetted point
  76745. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  76746. if (this._currentMeshSelected && !this._isTeleportationFloor(this._currentMeshSelected)) {
  76747. this._notifySelectedMeshUnselected();
  76748. }
  76749. this._currentMeshSelected = null;
  76750. this._moveTeleportationSelectorTo(hit);
  76751. return;
  76752. }
  76753. // If not, we're in a selection scenario
  76754. this._hideTeleportationTarget();
  76755. this._teleportationAllowed = false;
  76756. if (hit.pickedMesh !== this._currentMeshSelected) {
  76757. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  76758. this.onNewMeshPicked.notifyObservers(hit);
  76759. this._currentMeshSelected = hit.pickedMesh;
  76760. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  76761. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  76762. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  76763. this._isActionableMesh = true;
  76764. }
  76765. else {
  76766. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  76767. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  76768. this._isActionableMesh = false;
  76769. }
  76770. try {
  76771. this.onNewMeshSelected.notifyObservers(this._currentMeshSelected);
  76772. }
  76773. catch (err) {
  76774. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  76775. }
  76776. }
  76777. else {
  76778. this._notifySelectedMeshUnselected();
  76779. this._currentMeshSelected = null;
  76780. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  76781. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  76782. }
  76783. }
  76784. }
  76785. else {
  76786. this._currentHit = null;
  76787. this._notifySelectedMeshUnselected();
  76788. this._currentMeshSelected = null;
  76789. this._teleportationAllowed = false;
  76790. this._hideTeleportationTarget();
  76791. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  76792. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  76793. }
  76794. };
  76795. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function () {
  76796. if (this._currentMeshSelected) {
  76797. this.onSelectedMeshUnselected.notifyObservers(this._currentMeshSelected);
  76798. }
  76799. };
  76800. /**
  76801. * Sets the color of the laser ray from the vr controllers.
  76802. * @param color new color for the ray.
  76803. */
  76804. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  76805. if (this._leftLaserPointer && this._leftLaserPointer.material) {
  76806. this._leftLaserPointer.material.emissiveColor = color;
  76807. }
  76808. if (this._rightLaserPointer && this._rightLaserPointer.material) {
  76809. this._rightLaserPointer.material.emissiveColor = color;
  76810. }
  76811. };
  76812. /**
  76813. * Sets the color of the ray from the vr headsets gaze.
  76814. * @param color new color for the ray.
  76815. */
  76816. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  76817. if (this._gazeTracker.material) {
  76818. this._gazeTracker.material.emissiveColor = color;
  76819. }
  76820. };
  76821. /**
  76822. * Exits VR and disposes of the vr experience helper
  76823. */
  76824. VRExperienceHelper.prototype.dispose = function () {
  76825. if (this.isInVRMode) {
  76826. this.exitVR();
  76827. }
  76828. if (this._passProcessMove) {
  76829. this._passProcessMove.dispose();
  76830. }
  76831. if (this._postProcessMove) {
  76832. this._postProcessMove.dispose();
  76833. }
  76834. if (this._webVRCamera) {
  76835. this._webVRCamera.dispose();
  76836. }
  76837. if (this._vrDeviceOrientationCamera) {
  76838. this._vrDeviceOrientationCamera.dispose();
  76839. }
  76840. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  76841. document.body.removeChild(this._btnVR);
  76842. }
  76843. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  76844. this._deviceOrientationCamera.dispose();
  76845. }
  76846. if (this._gazeTracker) {
  76847. this._gazeTracker.dispose();
  76848. }
  76849. if (this._teleportationTarget) {
  76850. this._teleportationTarget.dispose();
  76851. }
  76852. this._floorMeshesCollection = [];
  76853. document.removeEventListener("keydown", this._onKeyDown);
  76854. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  76855. window.removeEventListener("resize", this._onResize);
  76856. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  76857. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  76858. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  76859. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  76860. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  76861. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  76862. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  76863. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  76864. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  76865. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  76866. this._scene.unregisterBeforeRender(this.beforeRender);
  76867. };
  76868. /**
  76869. * Gets the name of the VRExperienceHelper class
  76870. * @returns "VRExperienceHelper"
  76871. */
  76872. VRExperienceHelper.prototype.getClassName = function () {
  76873. return "VRExperienceHelper";
  76874. };
  76875. return VRExperienceHelper;
  76876. }());
  76877. BABYLON.VRExperienceHelper = VRExperienceHelper;
  76878. })(BABYLON || (BABYLON = {}));
  76879. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  76880. // Mainly based on these 2 articles :
  76881. // 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
  76882. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  76883. var BABYLON;
  76884. (function (BABYLON) {
  76885. var JoystickAxis;
  76886. (function (JoystickAxis) {
  76887. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  76888. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  76889. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  76890. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  76891. var VirtualJoystick = /** @class */ (function () {
  76892. function VirtualJoystick(leftJoystick) {
  76893. var _this = this;
  76894. if (leftJoystick) {
  76895. this._leftJoystick = true;
  76896. }
  76897. else {
  76898. this._leftJoystick = false;
  76899. }
  76900. VirtualJoystick._globalJoystickIndex++;
  76901. // By default left & right arrow keys are moving the X
  76902. // and up & down keys are moving the Y
  76903. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  76904. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  76905. this.reverseLeftRight = false;
  76906. this.reverseUpDown = false;
  76907. // collections of pointers
  76908. this._touches = new BABYLON.StringDictionary();
  76909. this.deltaPosition = BABYLON.Vector3.Zero();
  76910. this._joystickSensibility = 25;
  76911. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  76912. this._onResize = function (evt) {
  76913. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  76914. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  76915. if (VirtualJoystick.vjCanvas) {
  76916. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  76917. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  76918. }
  76919. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  76920. };
  76921. // injecting a canvas element on top of the canvas 3D game
  76922. if (!VirtualJoystick.vjCanvas) {
  76923. window.addEventListener("resize", this._onResize, false);
  76924. VirtualJoystick.vjCanvas = document.createElement("canvas");
  76925. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  76926. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  76927. VirtualJoystick.vjCanvas.width = window.innerWidth;
  76928. VirtualJoystick.vjCanvas.height = window.innerHeight;
  76929. VirtualJoystick.vjCanvas.style.width = "100%";
  76930. VirtualJoystick.vjCanvas.style.height = "100%";
  76931. VirtualJoystick.vjCanvas.style.position = "absolute";
  76932. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  76933. VirtualJoystick.vjCanvas.style.top = "0px";
  76934. VirtualJoystick.vjCanvas.style.left = "0px";
  76935. VirtualJoystick.vjCanvas.style.zIndex = "5";
  76936. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  76937. // Support for jQuery PEP polyfill
  76938. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  76939. var context = VirtualJoystick.vjCanvas.getContext('2d');
  76940. if (!context) {
  76941. throw new Error("Unable to create canvas for virtual joystick");
  76942. }
  76943. VirtualJoystick.vjCanvasContext = context;
  76944. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  76945. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  76946. document.body.appendChild(VirtualJoystick.vjCanvas);
  76947. }
  76948. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  76949. this.pressed = false;
  76950. // default joystick color
  76951. this._joystickColor = "cyan";
  76952. this._joystickPointerID = -1;
  76953. // current joystick position
  76954. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  76955. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  76956. // origin joystick position
  76957. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  76958. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  76959. this._onPointerDownHandlerRef = function (evt) {
  76960. _this._onPointerDown(evt);
  76961. };
  76962. this._onPointerMoveHandlerRef = function (evt) {
  76963. _this._onPointerMove(evt);
  76964. };
  76965. this._onPointerUpHandlerRef = function (evt) {
  76966. _this._onPointerUp(evt);
  76967. };
  76968. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  76969. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  76970. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  76971. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  76972. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  76973. evt.preventDefault(); // Disables system menu
  76974. }, false);
  76975. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  76976. }
  76977. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  76978. this._joystickSensibility = newJoystickSensibility;
  76979. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  76980. };
  76981. VirtualJoystick.prototype._onPointerDown = function (e) {
  76982. var positionOnScreenCondition;
  76983. e.preventDefault();
  76984. if (this._leftJoystick === true) {
  76985. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  76986. }
  76987. else {
  76988. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  76989. }
  76990. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  76991. // First contact will be dedicated to the virtual joystick
  76992. this._joystickPointerID = e.pointerId;
  76993. this._joystickPointerStartPos.x = e.clientX;
  76994. this._joystickPointerStartPos.y = e.clientY;
  76995. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  76996. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  76997. this._deltaJoystickVector.x = 0;
  76998. this._deltaJoystickVector.y = 0;
  76999. this.pressed = true;
  77000. this._touches.add(e.pointerId.toString(), e);
  77001. }
  77002. else {
  77003. // You can only trigger the action buttons with a joystick declared
  77004. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  77005. this._action();
  77006. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  77007. }
  77008. }
  77009. };
  77010. VirtualJoystick.prototype._onPointerMove = function (e) {
  77011. // If the current pointer is the one associated to the joystick (first touch contact)
  77012. if (this._joystickPointerID == e.pointerId) {
  77013. this._joystickPointerPos.x = e.clientX;
  77014. this._joystickPointerPos.y = e.clientY;
  77015. this._deltaJoystickVector = this._joystickPointerPos.clone();
  77016. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  77017. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  77018. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  77019. switch (this._axisTargetedByLeftAndRight) {
  77020. case JoystickAxis.X:
  77021. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  77022. break;
  77023. case JoystickAxis.Y:
  77024. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  77025. break;
  77026. case JoystickAxis.Z:
  77027. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  77028. break;
  77029. }
  77030. var directionUpDown = this.reverseUpDown ? 1 : -1;
  77031. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  77032. switch (this._axisTargetedByUpAndDown) {
  77033. case JoystickAxis.X:
  77034. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  77035. break;
  77036. case JoystickAxis.Y:
  77037. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  77038. break;
  77039. case JoystickAxis.Z:
  77040. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  77041. break;
  77042. }
  77043. }
  77044. else {
  77045. var data = this._touches.get(e.pointerId.toString());
  77046. if (data) {
  77047. data.x = e.clientX;
  77048. data.y = e.clientY;
  77049. }
  77050. }
  77051. };
  77052. VirtualJoystick.prototype._onPointerUp = function (e) {
  77053. if (this._joystickPointerID == e.pointerId) {
  77054. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  77055. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  77056. this._joystickPointerID = -1;
  77057. this.pressed = false;
  77058. }
  77059. else {
  77060. var touch = this._touches.get(e.pointerId.toString());
  77061. if (touch) {
  77062. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  77063. }
  77064. }
  77065. this._deltaJoystickVector.x = 0;
  77066. this._deltaJoystickVector.y = 0;
  77067. this._touches.remove(e.pointerId.toString());
  77068. };
  77069. /**
  77070. * Change the color of the virtual joystick
  77071. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  77072. */
  77073. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  77074. this._joystickColor = newColor;
  77075. };
  77076. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  77077. this._action = action;
  77078. };
  77079. // Define which axis you'd like to control for left & right
  77080. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  77081. switch (axis) {
  77082. case JoystickAxis.X:
  77083. case JoystickAxis.Y:
  77084. case JoystickAxis.Z:
  77085. this._axisTargetedByLeftAndRight = axis;
  77086. break;
  77087. default:
  77088. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  77089. break;
  77090. }
  77091. };
  77092. // Define which axis you'd like to control for up & down
  77093. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  77094. switch (axis) {
  77095. case JoystickAxis.X:
  77096. case JoystickAxis.Y:
  77097. case JoystickAxis.Z:
  77098. this._axisTargetedByUpAndDown = axis;
  77099. break;
  77100. default:
  77101. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  77102. break;
  77103. }
  77104. };
  77105. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  77106. var _this = this;
  77107. if (this.pressed) {
  77108. this._touches.forEach(function (key, touch) {
  77109. if (touch.pointerId === _this._joystickPointerID) {
  77110. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  77111. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  77112. VirtualJoystick.vjCanvasContext.beginPath();
  77113. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  77114. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  77115. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  77116. VirtualJoystick.vjCanvasContext.stroke();
  77117. VirtualJoystick.vjCanvasContext.closePath();
  77118. VirtualJoystick.vjCanvasContext.beginPath();
  77119. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  77120. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  77121. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  77122. VirtualJoystick.vjCanvasContext.stroke();
  77123. VirtualJoystick.vjCanvasContext.closePath();
  77124. VirtualJoystick.vjCanvasContext.beginPath();
  77125. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  77126. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  77127. VirtualJoystick.vjCanvasContext.stroke();
  77128. VirtualJoystick.vjCanvasContext.closePath();
  77129. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  77130. }
  77131. else {
  77132. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  77133. VirtualJoystick.vjCanvasContext.beginPath();
  77134. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  77135. VirtualJoystick.vjCanvasContext.beginPath();
  77136. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  77137. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  77138. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  77139. VirtualJoystick.vjCanvasContext.stroke();
  77140. VirtualJoystick.vjCanvasContext.closePath();
  77141. touch.prevX = touch.x;
  77142. touch.prevY = touch.y;
  77143. }
  77144. ;
  77145. });
  77146. }
  77147. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  77148. };
  77149. VirtualJoystick.prototype.releaseCanvas = function () {
  77150. if (VirtualJoystick.vjCanvas) {
  77151. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  77152. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  77153. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  77154. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  77155. window.removeEventListener("resize", this._onResize);
  77156. document.body.removeChild(VirtualJoystick.vjCanvas);
  77157. VirtualJoystick.vjCanvas = null;
  77158. }
  77159. };
  77160. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  77161. VirtualJoystick._globalJoystickIndex = 0;
  77162. return VirtualJoystick;
  77163. }());
  77164. BABYLON.VirtualJoystick = VirtualJoystick;
  77165. })(BABYLON || (BABYLON = {}));
  77166. //# sourceMappingURL=babylon.virtualJoystick.js.map
  77167. var BABYLON;
  77168. (function (BABYLON) {
  77169. // We're mainly based on the logic defined into the FreeCamera code
  77170. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  77171. __extends(VirtualJoysticksCamera, _super);
  77172. function VirtualJoysticksCamera(name, position, scene) {
  77173. var _this = _super.call(this, name, position, scene) || this;
  77174. _this.inputs.addVirtualJoystick();
  77175. return _this;
  77176. }
  77177. VirtualJoysticksCamera.prototype.getClassName = function () {
  77178. return "VirtualJoysticksCamera";
  77179. };
  77180. return VirtualJoysticksCamera;
  77181. }(BABYLON.FreeCamera));
  77182. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  77183. })(BABYLON || (BABYLON = {}));
  77184. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  77185. var BABYLON;
  77186. (function (BABYLON) {
  77187. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  77188. function FreeCameraVirtualJoystickInput() {
  77189. }
  77190. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  77191. return this._leftjoystick;
  77192. };
  77193. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  77194. return this._rightjoystick;
  77195. };
  77196. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  77197. if (this._leftjoystick) {
  77198. var camera = this.camera;
  77199. var speed = camera._computeLocalCameraSpeed() * 50;
  77200. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  77201. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  77202. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  77203. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  77204. if (!this._leftjoystick.pressed) {
  77205. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  77206. }
  77207. if (!this._rightjoystick.pressed) {
  77208. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  77209. }
  77210. }
  77211. };
  77212. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  77213. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  77214. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  77215. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  77216. this._leftjoystick.setJoystickSensibility(0.15);
  77217. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  77218. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  77219. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  77220. this._rightjoystick.reverseUpDown = true;
  77221. this._rightjoystick.setJoystickSensibility(0.05);
  77222. this._rightjoystick.setJoystickColor("yellow");
  77223. };
  77224. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  77225. this._leftjoystick.releaseCanvas();
  77226. this._rightjoystick.releaseCanvas();
  77227. };
  77228. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  77229. return "FreeCameraVirtualJoystickInput";
  77230. };
  77231. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  77232. return "virtualJoystick";
  77233. };
  77234. return FreeCameraVirtualJoystickInput;
  77235. }());
  77236. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  77237. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  77238. })(BABYLON || (BABYLON = {}));
  77239. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  77240. var BABYLON;
  77241. (function (BABYLON) {
  77242. var SimplificationSettings = /** @class */ (function () {
  77243. function SimplificationSettings(quality, distance, optimizeMesh) {
  77244. this.quality = quality;
  77245. this.distance = distance;
  77246. this.optimizeMesh = optimizeMesh;
  77247. }
  77248. return SimplificationSettings;
  77249. }());
  77250. BABYLON.SimplificationSettings = SimplificationSettings;
  77251. var SimplificationQueue = /** @class */ (function () {
  77252. function SimplificationQueue() {
  77253. this.running = false;
  77254. this._simplificationArray = [];
  77255. }
  77256. SimplificationQueue.prototype.addTask = function (task) {
  77257. this._simplificationArray.push(task);
  77258. };
  77259. SimplificationQueue.prototype.executeNext = function () {
  77260. var task = this._simplificationArray.pop();
  77261. if (task) {
  77262. this.running = true;
  77263. this.runSimplification(task);
  77264. }
  77265. else {
  77266. this.running = false;
  77267. }
  77268. };
  77269. SimplificationQueue.prototype.runSimplification = function (task) {
  77270. var _this = this;
  77271. if (task.parallelProcessing) {
  77272. //parallel simplifier
  77273. task.settings.forEach(function (setting) {
  77274. var simplifier = _this.getSimplifier(task);
  77275. simplifier.simplify(setting, function (newMesh) {
  77276. task.mesh.addLODLevel(setting.distance, newMesh);
  77277. newMesh.isVisible = true;
  77278. //check if it is the last
  77279. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  77280. //all done, run the success callback.
  77281. task.successCallback();
  77282. }
  77283. _this.executeNext();
  77284. });
  77285. });
  77286. }
  77287. else {
  77288. //single simplifier.
  77289. var simplifier = this.getSimplifier(task);
  77290. var runDecimation = function (setting, callback) {
  77291. simplifier.simplify(setting, function (newMesh) {
  77292. task.mesh.addLODLevel(setting.distance, newMesh);
  77293. newMesh.isVisible = true;
  77294. //run the next quality level
  77295. callback();
  77296. });
  77297. };
  77298. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  77299. runDecimation(task.settings[loop.index], function () {
  77300. loop.executeNext();
  77301. });
  77302. }, function () {
  77303. //execution ended, run the success callback.
  77304. if (task.successCallback) {
  77305. task.successCallback();
  77306. }
  77307. _this.executeNext();
  77308. });
  77309. }
  77310. };
  77311. SimplificationQueue.prototype.getSimplifier = function (task) {
  77312. switch (task.simplificationType) {
  77313. case SimplificationType.QUADRATIC:
  77314. default:
  77315. return new QuadraticErrorSimplification(task.mesh);
  77316. }
  77317. };
  77318. return SimplificationQueue;
  77319. }());
  77320. BABYLON.SimplificationQueue = SimplificationQueue;
  77321. /**
  77322. * The implemented types of simplification.
  77323. * At the moment only Quadratic Error Decimation is implemented.
  77324. */
  77325. var SimplificationType;
  77326. (function (SimplificationType) {
  77327. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  77328. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  77329. var DecimationTriangle = /** @class */ (function () {
  77330. function DecimationTriangle(vertices) {
  77331. this.vertices = vertices;
  77332. this.error = new Array(4);
  77333. this.deleted = false;
  77334. this.isDirty = false;
  77335. this.deletePending = false;
  77336. this.borderFactor = 0;
  77337. }
  77338. return DecimationTriangle;
  77339. }());
  77340. BABYLON.DecimationTriangle = DecimationTriangle;
  77341. var DecimationVertex = /** @class */ (function () {
  77342. function DecimationVertex(position, id) {
  77343. this.position = position;
  77344. this.id = id;
  77345. this.isBorder = true;
  77346. this.q = new QuadraticMatrix();
  77347. this.triangleCount = 0;
  77348. this.triangleStart = 0;
  77349. this.originalOffsets = [];
  77350. }
  77351. DecimationVertex.prototype.updatePosition = function (newPosition) {
  77352. this.position.copyFrom(newPosition);
  77353. };
  77354. return DecimationVertex;
  77355. }());
  77356. BABYLON.DecimationVertex = DecimationVertex;
  77357. var QuadraticMatrix = /** @class */ (function () {
  77358. function QuadraticMatrix(data) {
  77359. this.data = new Array(10);
  77360. for (var i = 0; i < 10; ++i) {
  77361. if (data && data[i]) {
  77362. this.data[i] = data[i];
  77363. }
  77364. else {
  77365. this.data[i] = 0;
  77366. }
  77367. }
  77368. }
  77369. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  77370. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  77371. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  77372. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  77373. return det;
  77374. };
  77375. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  77376. for (var i = 0; i < 10; ++i) {
  77377. this.data[i] += matrix.data[i];
  77378. }
  77379. };
  77380. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  77381. for (var i = 0; i < 10; ++i) {
  77382. this.data[i] += data[i];
  77383. }
  77384. };
  77385. QuadraticMatrix.prototype.add = function (matrix) {
  77386. var m = new QuadraticMatrix();
  77387. for (var i = 0; i < 10; ++i) {
  77388. m.data[i] = this.data[i] + matrix.data[i];
  77389. }
  77390. return m;
  77391. };
  77392. QuadraticMatrix.FromData = function (a, b, c, d) {
  77393. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  77394. };
  77395. //returning an array to avoid garbage collection
  77396. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  77397. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  77398. };
  77399. return QuadraticMatrix;
  77400. }());
  77401. BABYLON.QuadraticMatrix = QuadraticMatrix;
  77402. var Reference = /** @class */ (function () {
  77403. function Reference(vertexId, triangleId) {
  77404. this.vertexId = vertexId;
  77405. this.triangleId = triangleId;
  77406. }
  77407. return Reference;
  77408. }());
  77409. BABYLON.Reference = Reference;
  77410. /**
  77411. * An implementation of the Quadratic Error simplification algorithm.
  77412. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  77413. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  77414. * @author RaananW
  77415. */
  77416. var QuadraticErrorSimplification = /** @class */ (function () {
  77417. function QuadraticErrorSimplification(_mesh) {
  77418. this._mesh = _mesh;
  77419. this.syncIterations = 5000;
  77420. this.aggressiveness = 7;
  77421. this.decimationIterations = 100;
  77422. this.boundingBoxEpsilon = BABYLON.Epsilon;
  77423. }
  77424. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  77425. var _this = this;
  77426. this.initDecimatedMesh();
  77427. //iterating through the submeshes array, one after the other.
  77428. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  77429. _this.initWithMesh(loop.index, function () {
  77430. _this.runDecimation(settings, loop.index, function () {
  77431. loop.executeNext();
  77432. });
  77433. }, settings.optimizeMesh);
  77434. }, function () {
  77435. setTimeout(function () {
  77436. successCallback(_this._reconstructedMesh);
  77437. }, 0);
  77438. });
  77439. };
  77440. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  77441. var _this = this;
  77442. var targetCount = ~~(this.triangles.length * settings.quality);
  77443. var deletedTriangles = 0;
  77444. var triangleCount = this.triangles.length;
  77445. var iterationFunction = function (iteration, callback) {
  77446. setTimeout(function () {
  77447. if (iteration % 5 === 0) {
  77448. _this.updateMesh(iteration === 0);
  77449. }
  77450. for (var i = 0; i < _this.triangles.length; ++i) {
  77451. _this.triangles[i].isDirty = false;
  77452. }
  77453. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  77454. var trianglesIterator = function (i) {
  77455. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  77456. var t = _this.triangles[tIdx];
  77457. if (!t)
  77458. return;
  77459. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  77460. return;
  77461. }
  77462. for (var j = 0; j < 3; ++j) {
  77463. if (t.error[j] < threshold) {
  77464. var deleted0 = [];
  77465. var deleted1 = [];
  77466. var v0 = t.vertices[j];
  77467. var v1 = t.vertices[(j + 1) % 3];
  77468. if (v0.isBorder || v1.isBorder)
  77469. continue;
  77470. var p = BABYLON.Vector3.Zero();
  77471. var n = BABYLON.Vector3.Zero();
  77472. var uv = BABYLON.Vector2.Zero();
  77473. var color = new BABYLON.Color4(0, 0, 0, 1);
  77474. _this.calculateError(v0, v1, p, n, uv, color);
  77475. var delTr = new Array();
  77476. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  77477. continue;
  77478. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  77479. continue;
  77480. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  77481. continue;
  77482. var uniqueArray = new Array();
  77483. delTr.forEach(function (deletedT) {
  77484. if (uniqueArray.indexOf(deletedT) === -1) {
  77485. deletedT.deletePending = true;
  77486. uniqueArray.push(deletedT);
  77487. }
  77488. });
  77489. if (uniqueArray.length % 2 !== 0) {
  77490. continue;
  77491. }
  77492. v0.q = v1.q.add(v0.q);
  77493. v0.updatePosition(p);
  77494. var tStart = _this.references.length;
  77495. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  77496. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  77497. var tCount = _this.references.length - tStart;
  77498. if (tCount <= v0.triangleCount) {
  77499. if (tCount) {
  77500. for (var c = 0; c < tCount; c++) {
  77501. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  77502. }
  77503. }
  77504. }
  77505. else {
  77506. v0.triangleStart = tStart;
  77507. }
  77508. v0.triangleCount = tCount;
  77509. break;
  77510. }
  77511. }
  77512. };
  77513. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  77514. }, 0);
  77515. };
  77516. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  77517. if (triangleCount - deletedTriangles <= targetCount)
  77518. loop.breakLoop();
  77519. else {
  77520. iterationFunction(loop.index, function () {
  77521. loop.executeNext();
  77522. });
  77523. }
  77524. }, function () {
  77525. setTimeout(function () {
  77526. //reconstruct this part of the mesh
  77527. _this.reconstructMesh(submeshIndex);
  77528. successCallback();
  77529. }, 0);
  77530. });
  77531. };
  77532. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  77533. var _this = this;
  77534. this.vertices = [];
  77535. this.triangles = [];
  77536. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  77537. var indices = this._mesh.getIndices();
  77538. var submesh = this._mesh.subMeshes[submeshIndex];
  77539. var findInVertices = function (positionToSearch) {
  77540. if (optimizeMesh) {
  77541. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  77542. if (_this.vertices[ii].position.equals(positionToSearch)) {
  77543. return _this.vertices[ii];
  77544. }
  77545. }
  77546. }
  77547. return null;
  77548. };
  77549. var vertexReferences = [];
  77550. var vertexInit = function (i) {
  77551. if (!positionData) {
  77552. return;
  77553. }
  77554. var offset = i + submesh.verticesStart;
  77555. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  77556. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  77557. vertex.originalOffsets.push(offset);
  77558. if (vertex.id === _this.vertices.length) {
  77559. _this.vertices.push(vertex);
  77560. }
  77561. vertexReferences.push(vertex.id);
  77562. };
  77563. //var totalVertices = mesh.getTotalVertices();
  77564. var totalVertices = submesh.verticesCount;
  77565. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  77566. var indicesInit = function (i) {
  77567. if (!indices) {
  77568. return;
  77569. }
  77570. var offset = (submesh.indexStart / 3) + i;
  77571. var pos = (offset * 3);
  77572. var i0 = indices[pos + 0];
  77573. var i1 = indices[pos + 1];
  77574. var i2 = indices[pos + 2];
  77575. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  77576. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  77577. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  77578. var triangle = new DecimationTriangle([v0, v1, v2]);
  77579. triangle.originalOffset = pos;
  77580. _this.triangles.push(triangle);
  77581. };
  77582. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  77583. _this.init(callback);
  77584. });
  77585. });
  77586. };
  77587. QuadraticErrorSimplification.prototype.init = function (callback) {
  77588. var _this = this;
  77589. var triangleInit1 = function (i) {
  77590. var t = _this.triangles[i];
  77591. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  77592. for (var j = 0; j < 3; j++) {
  77593. 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))));
  77594. }
  77595. };
  77596. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  77597. var triangleInit2 = function (i) {
  77598. var t = _this.triangles[i];
  77599. for (var j = 0; j < 3; ++j) {
  77600. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  77601. }
  77602. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  77603. };
  77604. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  77605. callback();
  77606. });
  77607. });
  77608. };
  77609. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  77610. var newTriangles = [];
  77611. var i;
  77612. for (i = 0; i < this.vertices.length; ++i) {
  77613. this.vertices[i].triangleCount = 0;
  77614. }
  77615. var t;
  77616. var j;
  77617. for (i = 0; i < this.triangles.length; ++i) {
  77618. if (!this.triangles[i].deleted) {
  77619. t = this.triangles[i];
  77620. for (j = 0; j < 3; ++j) {
  77621. t.vertices[j].triangleCount = 1;
  77622. }
  77623. newTriangles.push(t);
  77624. }
  77625. }
  77626. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  77627. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  77628. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  77629. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  77630. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  77631. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  77632. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  77633. var vertexCount = 0;
  77634. for (i = 0; i < this.vertices.length; ++i) {
  77635. var vertex = this.vertices[i];
  77636. vertex.id = vertexCount;
  77637. if (vertex.triangleCount) {
  77638. vertex.originalOffsets.forEach(function (originalOffset) {
  77639. if (!normalData) {
  77640. return;
  77641. }
  77642. newPositionData.push(vertex.position.x);
  77643. newPositionData.push(vertex.position.y);
  77644. newPositionData.push(vertex.position.z);
  77645. newNormalData.push(normalData[originalOffset * 3]);
  77646. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  77647. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  77648. if (uvs && uvs.length) {
  77649. newUVsData.push(uvs[(originalOffset * 2)]);
  77650. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  77651. }
  77652. else if (colorsData && colorsData.length) {
  77653. newColorsData.push(colorsData[(originalOffset * 4)]);
  77654. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  77655. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  77656. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  77657. }
  77658. ++vertexCount;
  77659. });
  77660. }
  77661. }
  77662. var startingIndex = this._reconstructedMesh.getTotalIndices();
  77663. var startingVertex = this._reconstructedMesh.getTotalVertices();
  77664. var submeshesArray = this._reconstructedMesh.subMeshes;
  77665. this._reconstructedMesh.subMeshes = [];
  77666. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  77667. var originalIndices = this._mesh.getIndices();
  77668. for (i = 0; i < newTriangles.length; ++i) {
  77669. t = newTriangles[i]; //now get the new referencing point for each vertex
  77670. [0, 1, 2].forEach(function (idx) {
  77671. var id = originalIndices[t.originalOffset + idx];
  77672. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  77673. if (offset < 0)
  77674. offset = 0;
  77675. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  77676. });
  77677. }
  77678. //overwriting the old vertex buffers and indices.
  77679. this._reconstructedMesh.setIndices(newIndicesArray);
  77680. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  77681. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  77682. if (newUVsData.length > 0)
  77683. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  77684. if (newColorsData.length > 0)
  77685. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  77686. //create submesh
  77687. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  77688. if (submeshIndex > 0) {
  77689. this._reconstructedMesh.subMeshes = [];
  77690. submeshesArray.forEach(function (submesh) {
  77691. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  77692. });
  77693. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  77694. }
  77695. };
  77696. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  77697. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  77698. this._reconstructedMesh.material = this._mesh.material;
  77699. this._reconstructedMesh.parent = this._mesh.parent;
  77700. this._reconstructedMesh.isVisible = false;
  77701. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  77702. };
  77703. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  77704. for (var i = 0; i < vertex1.triangleCount; ++i) {
  77705. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  77706. if (t.deleted)
  77707. continue;
  77708. var s = this.references[vertex1.triangleStart + i].vertexId;
  77709. var v1 = t.vertices[(s + 1) % 3];
  77710. var v2 = t.vertices[(s + 2) % 3];
  77711. if ((v1 === vertex2 || v2 === vertex2)) {
  77712. deletedArray[i] = true;
  77713. delTr.push(t);
  77714. continue;
  77715. }
  77716. var d1 = v1.position.subtract(point);
  77717. d1 = d1.normalize();
  77718. var d2 = v2.position.subtract(point);
  77719. d2 = d2.normalize();
  77720. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  77721. return true;
  77722. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  77723. deletedArray[i] = false;
  77724. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  77725. return true;
  77726. }
  77727. return false;
  77728. };
  77729. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  77730. var newDeleted = deletedTriangles;
  77731. for (var i = 0; i < vertex.triangleCount; ++i) {
  77732. var ref = this.references[vertex.triangleStart + i];
  77733. var t = this.triangles[ref.triangleId];
  77734. if (t.deleted)
  77735. continue;
  77736. if (deletedArray[i] && t.deletePending) {
  77737. t.deleted = true;
  77738. newDeleted++;
  77739. continue;
  77740. }
  77741. t.vertices[ref.vertexId] = origVertex;
  77742. t.isDirty = true;
  77743. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  77744. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  77745. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  77746. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  77747. this.references.push(ref);
  77748. }
  77749. return newDeleted;
  77750. };
  77751. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  77752. for (var i = 0; i < this.vertices.length; ++i) {
  77753. var vCount = [];
  77754. var vId = [];
  77755. var v = this.vertices[i];
  77756. var j;
  77757. for (j = 0; j < v.triangleCount; ++j) {
  77758. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  77759. for (var ii = 0; ii < 3; ii++) {
  77760. var ofs = 0;
  77761. var vv = triangle.vertices[ii];
  77762. while (ofs < vCount.length) {
  77763. if (vId[ofs] === vv.id)
  77764. break;
  77765. ++ofs;
  77766. }
  77767. if (ofs === vCount.length) {
  77768. vCount.push(1);
  77769. vId.push(vv.id);
  77770. }
  77771. else {
  77772. vCount[ofs]++;
  77773. }
  77774. }
  77775. }
  77776. for (j = 0; j < vCount.length; ++j) {
  77777. if (vCount[j] === 1) {
  77778. this.vertices[vId[j]].isBorder = true;
  77779. }
  77780. else {
  77781. this.vertices[vId[j]].isBorder = false;
  77782. }
  77783. }
  77784. }
  77785. };
  77786. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  77787. if (identifyBorders === void 0) { identifyBorders = false; }
  77788. var i;
  77789. if (!identifyBorders) {
  77790. var newTrianglesVector = [];
  77791. for (i = 0; i < this.triangles.length; ++i) {
  77792. if (!this.triangles[i].deleted) {
  77793. newTrianglesVector.push(this.triangles[i]);
  77794. }
  77795. }
  77796. this.triangles = newTrianglesVector;
  77797. }
  77798. for (i = 0; i < this.vertices.length; ++i) {
  77799. this.vertices[i].triangleCount = 0;
  77800. this.vertices[i].triangleStart = 0;
  77801. }
  77802. var t;
  77803. var j;
  77804. var v;
  77805. for (i = 0; i < this.triangles.length; ++i) {
  77806. t = this.triangles[i];
  77807. for (j = 0; j < 3; ++j) {
  77808. v = t.vertices[j];
  77809. v.triangleCount++;
  77810. }
  77811. }
  77812. var tStart = 0;
  77813. for (i = 0; i < this.vertices.length; ++i) {
  77814. this.vertices[i].triangleStart = tStart;
  77815. tStart += this.vertices[i].triangleCount;
  77816. this.vertices[i].triangleCount = 0;
  77817. }
  77818. var newReferences = new Array(this.triangles.length * 3);
  77819. for (i = 0; i < this.triangles.length; ++i) {
  77820. t = this.triangles[i];
  77821. for (j = 0; j < 3; ++j) {
  77822. v = t.vertices[j];
  77823. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  77824. v.triangleCount++;
  77825. }
  77826. }
  77827. this.references = newReferences;
  77828. if (identifyBorders) {
  77829. this.identifyBorder();
  77830. }
  77831. };
  77832. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  77833. var x = point.x;
  77834. var y = point.y;
  77835. var z = point.z;
  77836. 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
  77837. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  77838. };
  77839. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  77840. var q = vertex1.q.add(vertex2.q);
  77841. var border = vertex1.isBorder && vertex2.isBorder;
  77842. var error = 0;
  77843. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  77844. if (qDet !== 0 && !border) {
  77845. if (!pointResult) {
  77846. pointResult = BABYLON.Vector3.Zero();
  77847. }
  77848. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  77849. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  77850. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  77851. error = this.vertexError(q, pointResult);
  77852. }
  77853. else {
  77854. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  77855. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  77856. var error1 = this.vertexError(q, vertex1.position);
  77857. var error2 = this.vertexError(q, vertex2.position);
  77858. var error3 = this.vertexError(q, p3);
  77859. error = Math.min(error1, error2, error3);
  77860. if (error === error1) {
  77861. if (pointResult) {
  77862. pointResult.copyFrom(vertex1.position);
  77863. }
  77864. }
  77865. else if (error === error2) {
  77866. if (pointResult) {
  77867. pointResult.copyFrom(vertex2.position);
  77868. }
  77869. }
  77870. else {
  77871. if (pointResult) {
  77872. pointResult.copyFrom(p3);
  77873. }
  77874. }
  77875. }
  77876. return error;
  77877. };
  77878. return QuadraticErrorSimplification;
  77879. }());
  77880. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  77881. })(BABYLON || (BABYLON = {}));
  77882. //# sourceMappingURL=babylon.meshSimplification.js.map
  77883. var BABYLON;
  77884. (function (BABYLON) {
  77885. var MeshLODLevel = /** @class */ (function () {
  77886. function MeshLODLevel(distance, mesh) {
  77887. this.distance = distance;
  77888. this.mesh = mesh;
  77889. }
  77890. return MeshLODLevel;
  77891. }());
  77892. BABYLON.MeshLODLevel = MeshLODLevel;
  77893. })(BABYLON || (BABYLON = {}));
  77894. //# sourceMappingURL=babylon.meshLODLevel.js.map
  77895. var BABYLON;
  77896. (function (BABYLON) {
  77897. /**
  77898. * Defines the root class used to create scene optimization to use with SceneOptimizer
  77899. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  77900. */
  77901. var SceneOptimization = /** @class */ (function () {
  77902. /**
  77903. * Creates the SceneOptimization object
  77904. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  77905. * @param desc defines the description associated with the optimization
  77906. */
  77907. function SceneOptimization(
  77908. /**
  77909. * Defines the priority of this optimization (0 by default which means first in the list)
  77910. */
  77911. priority) {
  77912. if (priority === void 0) { priority = 0; }
  77913. this.priority = priority;
  77914. }
  77915. /**
  77916. * Gets a string describing the action executed by the current optimization
  77917. * @returns description string
  77918. */
  77919. SceneOptimization.prototype.getDescription = function () {
  77920. return "";
  77921. };
  77922. /**
  77923. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  77924. * @param scene defines the current scene where to apply this optimization
  77925. * @param optimizer defines the current optimizer
  77926. * @returns true if everything that can be done was applied
  77927. */
  77928. SceneOptimization.prototype.apply = function (scene, optimizer) {
  77929. return true;
  77930. };
  77931. ;
  77932. return SceneOptimization;
  77933. }());
  77934. BABYLON.SceneOptimization = SceneOptimization;
  77935. /**
  77936. * Defines an optimization used to reduce the size of render target textures
  77937. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  77938. */
  77939. var TextureOptimization = /** @class */ (function (_super) {
  77940. __extends(TextureOptimization, _super);
  77941. /**
  77942. * Creates the TextureOptimization object
  77943. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  77944. * @param maximumSize defines the maximum sized allowed for textures (1024 is the default value). If a texture is bigger, it will be scaled down using a factor defined by the step parameter
  77945. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  77946. */
  77947. function TextureOptimization(
  77948. /**
  77949. * Defines the priority of this optimization (0 by default which means first in the list)
  77950. */
  77951. priority,
  77952. /**
  77953. * Defines the maximum sized allowed for textures (1024 is the default value). If a texture is bigger, it will be scaled down using a factor defined by the step parameter
  77954. */
  77955. maximumSize,
  77956. /**
  77957. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  77958. */
  77959. step) {
  77960. if (priority === void 0) { priority = 0; }
  77961. if (maximumSize === void 0) { maximumSize = 1024; }
  77962. if (step === void 0) { step = 0.5; }
  77963. var _this = _super.call(this, priority) || this;
  77964. _this.priority = priority;
  77965. _this.maximumSize = maximumSize;
  77966. _this.step = step;
  77967. return _this;
  77968. }
  77969. /**
  77970. * Gets a string describing the action executed by the current optimization
  77971. * @returns description string
  77972. */
  77973. TextureOptimization.prototype.getDescription = function () {
  77974. return "Reducing render target texture size to " + this.maximumSize;
  77975. };
  77976. /**
  77977. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  77978. * @param scene defines the current scene where to apply this optimization
  77979. * @param optimizer defines the current optimizer
  77980. * @returns true if everything that can be done was applied
  77981. */
  77982. TextureOptimization.prototype.apply = function (scene, optimizer) {
  77983. var allDone = true;
  77984. for (var index = 0; index < scene.textures.length; index++) {
  77985. var texture = scene.textures[index];
  77986. if (!texture.canRescale || texture.getContext) {
  77987. continue;
  77988. }
  77989. var currentSize = texture.getSize();
  77990. var maxDimension = Math.max(currentSize.width, currentSize.height);
  77991. if (maxDimension > this.maximumSize) {
  77992. texture.scale(this.step);
  77993. allDone = false;
  77994. }
  77995. }
  77996. return allDone;
  77997. };
  77998. return TextureOptimization;
  77999. }(SceneOptimization));
  78000. BABYLON.TextureOptimization = TextureOptimization;
  78001. /**
  78002. * Defines an optimization used to increase or decrease the rendering resolution
  78003. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  78004. */
  78005. var HardwareScalingOptimization = /** @class */ (function (_super) {
  78006. __extends(HardwareScalingOptimization, _super);
  78007. /**
  78008. * Creates the HardwareScalingOptimization object
  78009. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  78010. * @param maximumScale defines the maximum scale to use (2 by default)
  78011. * @param step defines the step to use between two passes (0.5 by default)
  78012. */
  78013. function HardwareScalingOptimization(
  78014. /**
  78015. * Defines the priority of this optimization (0 by default which means first in the list)
  78016. */
  78017. priority,
  78018. /**
  78019. * Defines the maximum scale to use (2 by default)
  78020. */
  78021. maximumScale,
  78022. /**
  78023. * Defines the step to use between two passes (0.5 by default)
  78024. */
  78025. step) {
  78026. if (priority === void 0) { priority = 0; }
  78027. if (maximumScale === void 0) { maximumScale = 2; }
  78028. if (step === void 0) { step = 0.25; }
  78029. var _this = _super.call(this, priority) || this;
  78030. _this.priority = priority;
  78031. _this.maximumScale = maximumScale;
  78032. _this.step = step;
  78033. _this._currentScale = -1;
  78034. _this._directionOffset = 1;
  78035. return _this;
  78036. }
  78037. /**
  78038. * Gets a string describing the action executed by the current optimization
  78039. * @return description string
  78040. */
  78041. HardwareScalingOptimization.prototype.getDescription = function () {
  78042. return "Setting hardware scaling level to " + this._currentScale;
  78043. };
  78044. /**
  78045. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  78046. * @param scene defines the current scene where to apply this optimization
  78047. * @param optimizer defines the current optimizer
  78048. * @returns true if everything that can be done was applied
  78049. */
  78050. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  78051. if (this._currentScale === -1) {
  78052. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  78053. if (this._currentScale > this.maximumScale) {
  78054. this._directionOffset = -1;
  78055. }
  78056. }
  78057. this._currentScale += this._directionOffset * this.step;
  78058. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  78059. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  78060. };
  78061. ;
  78062. return HardwareScalingOptimization;
  78063. }(SceneOptimization));
  78064. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  78065. /**
  78066. * Defines an optimization used to remove shadows
  78067. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  78068. */
  78069. var ShadowsOptimization = /** @class */ (function (_super) {
  78070. __extends(ShadowsOptimization, _super);
  78071. function ShadowsOptimization() {
  78072. return _super !== null && _super.apply(this, arguments) || this;
  78073. }
  78074. /**
  78075. * Gets a string describing the action executed by the current optimization
  78076. * @return description string
  78077. */
  78078. ShadowsOptimization.prototype.getDescription = function () {
  78079. return "Turning shadows on/off";
  78080. };
  78081. /**
  78082. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  78083. * @param scene defines the current scene where to apply this optimization
  78084. * @param optimizer defines the current optimizer
  78085. * @returns true if everything that can be done was applied
  78086. */
  78087. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  78088. scene.shadowsEnabled = optimizer.isInImprovementMode;
  78089. return true;
  78090. };
  78091. ;
  78092. return ShadowsOptimization;
  78093. }(SceneOptimization));
  78094. BABYLON.ShadowsOptimization = ShadowsOptimization;
  78095. /**
  78096. * Defines an optimization used to turn post-processes off
  78097. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  78098. */
  78099. var PostProcessesOptimization = /** @class */ (function (_super) {
  78100. __extends(PostProcessesOptimization, _super);
  78101. function PostProcessesOptimization() {
  78102. return _super !== null && _super.apply(this, arguments) || this;
  78103. }
  78104. /**
  78105. * Gets a string describing the action executed by the current optimization
  78106. * @return description string
  78107. */
  78108. PostProcessesOptimization.prototype.getDescription = function () {
  78109. return "Turning post-processes on/off";
  78110. };
  78111. /**
  78112. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  78113. * @param scene defines the current scene where to apply this optimization
  78114. * @param optimizer defines the current optimizer
  78115. * @returns true if everything that can be done was applied
  78116. */
  78117. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  78118. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  78119. return true;
  78120. };
  78121. ;
  78122. return PostProcessesOptimization;
  78123. }(SceneOptimization));
  78124. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  78125. /**
  78126. * Defines an optimization used to turn lens flares off
  78127. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  78128. */
  78129. var LensFlaresOptimization = /** @class */ (function (_super) {
  78130. __extends(LensFlaresOptimization, _super);
  78131. function LensFlaresOptimization() {
  78132. return _super !== null && _super.apply(this, arguments) || this;
  78133. }
  78134. /**
  78135. * Gets a string describing the action executed by the current optimization
  78136. * @return description string
  78137. */
  78138. LensFlaresOptimization.prototype.getDescription = function () {
  78139. return "Turning lens flares on/off";
  78140. };
  78141. /**
  78142. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  78143. * @param scene defines the current scene where to apply this optimization
  78144. * @param optimizer defines the current optimizer
  78145. * @returns true if everything that can be done was applied
  78146. */
  78147. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  78148. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  78149. return true;
  78150. };
  78151. ;
  78152. return LensFlaresOptimization;
  78153. }(SceneOptimization));
  78154. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  78155. /**
  78156. * Defines an optimization based on user defined callback.
  78157. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  78158. */
  78159. var CustomOptimization = /** @class */ (function (_super) {
  78160. __extends(CustomOptimization, _super);
  78161. function CustomOptimization() {
  78162. return _super !== null && _super.apply(this, arguments) || this;
  78163. }
  78164. /**
  78165. * Gets a string describing the action executed by the current optimization
  78166. * @returns description string
  78167. */
  78168. CustomOptimization.prototype.getDescription = function () {
  78169. if (this.onGetDescription) {
  78170. return this.onGetDescription();
  78171. }
  78172. return "Running user defined callback";
  78173. };
  78174. /**
  78175. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  78176. * @param scene defines the current scene where to apply this optimization
  78177. * @param optimizer defines the current optimizer
  78178. * @returns true if everything that can be done was applied
  78179. */
  78180. CustomOptimization.prototype.apply = function (scene, optimizer) {
  78181. if (this.onApply) {
  78182. return this.onApply(scene, optimizer);
  78183. }
  78184. return true;
  78185. };
  78186. ;
  78187. return CustomOptimization;
  78188. }(SceneOptimization));
  78189. BABYLON.CustomOptimization = CustomOptimization;
  78190. /**
  78191. * Defines an optimization used to turn particles off
  78192. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  78193. */
  78194. var ParticlesOptimization = /** @class */ (function (_super) {
  78195. __extends(ParticlesOptimization, _super);
  78196. function ParticlesOptimization() {
  78197. return _super !== null && _super.apply(this, arguments) || this;
  78198. }
  78199. /**
  78200. * Gets a string describing the action executed by the current optimization
  78201. * @return description string
  78202. */
  78203. ParticlesOptimization.prototype.getDescription = function () {
  78204. return "Turning particles on/off";
  78205. };
  78206. /**
  78207. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  78208. * @param scene defines the current scene where to apply this optimization
  78209. * @param optimizer defines the current optimizer
  78210. * @returns true if everything that can be done was applied
  78211. */
  78212. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  78213. scene.particlesEnabled = optimizer.isInImprovementMode;
  78214. return true;
  78215. };
  78216. ;
  78217. return ParticlesOptimization;
  78218. }(SceneOptimization));
  78219. BABYLON.ParticlesOptimization = ParticlesOptimization;
  78220. /**
  78221. * Defines an optimization used to turn render targets off
  78222. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  78223. */
  78224. var RenderTargetsOptimization = /** @class */ (function (_super) {
  78225. __extends(RenderTargetsOptimization, _super);
  78226. function RenderTargetsOptimization() {
  78227. return _super !== null && _super.apply(this, arguments) || this;
  78228. }
  78229. /**
  78230. * Gets a string describing the action executed by the current optimization
  78231. * @return description string
  78232. */
  78233. RenderTargetsOptimization.prototype.getDescription = function () {
  78234. return "Turning render targets off";
  78235. };
  78236. /**
  78237. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  78238. * @param scene defines the current scene where to apply this optimization
  78239. * @param optimizer defines the current optimizer
  78240. * @returns true if everything that can be done was applied
  78241. */
  78242. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  78243. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  78244. return true;
  78245. };
  78246. ;
  78247. return RenderTargetsOptimization;
  78248. }(SceneOptimization));
  78249. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  78250. /**
  78251. * Defines an optimization used to merge meshes with compatible materials
  78252. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  78253. */
  78254. var MergeMeshesOptimization = /** @class */ (function (_super) {
  78255. __extends(MergeMeshesOptimization, _super);
  78256. function MergeMeshesOptimization() {
  78257. var _this = _super !== null && _super.apply(this, arguments) || this;
  78258. _this._canBeMerged = function (abstractMesh) {
  78259. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  78260. return false;
  78261. }
  78262. var mesh = abstractMesh;
  78263. if (!mesh.isVisible || !mesh.isEnabled()) {
  78264. return false;
  78265. }
  78266. if (mesh.instances.length > 0) {
  78267. return false;
  78268. }
  78269. if (mesh.skeleton || mesh.hasLODLevels) {
  78270. return false;
  78271. }
  78272. if (mesh.parent) {
  78273. return false;
  78274. }
  78275. return true;
  78276. };
  78277. return _this;
  78278. }
  78279. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  78280. /**
  78281. * Gets or sets a boolean which defines if optimization octree has to be updated
  78282. */
  78283. get: function () {
  78284. return MergeMeshesOptimization._UpdateSelectionTree;
  78285. },
  78286. /**
  78287. * Gets or sets a boolean which defines if optimization octree has to be updated
  78288. */
  78289. set: function (value) {
  78290. MergeMeshesOptimization._UpdateSelectionTree = value;
  78291. },
  78292. enumerable: true,
  78293. configurable: true
  78294. });
  78295. /**
  78296. * Gets a string describing the action executed by the current optimization
  78297. * @return description string
  78298. */
  78299. MergeMeshesOptimization.prototype.getDescription = function () {
  78300. return "Merging similar meshes together";
  78301. };
  78302. /**
  78303. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  78304. * @param scene defines the current scene where to apply this optimization
  78305. * @param optimizer defines the current optimizer
  78306. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  78307. * @returns true if everything that can be done was applied
  78308. */
  78309. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  78310. var globalPool = scene.meshes.slice(0);
  78311. var globalLength = globalPool.length;
  78312. for (var index = 0; index < globalLength; index++) {
  78313. var currentPool = new Array();
  78314. var current = globalPool[index];
  78315. // Checks
  78316. if (!this._canBeMerged(current)) {
  78317. continue;
  78318. }
  78319. currentPool.push(current);
  78320. // Find compatible meshes
  78321. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  78322. var otherMesh = globalPool[subIndex];
  78323. if (!this._canBeMerged(otherMesh)) {
  78324. continue;
  78325. }
  78326. if (otherMesh.material !== current.material) {
  78327. continue;
  78328. }
  78329. if (otherMesh.checkCollisions !== current.checkCollisions) {
  78330. continue;
  78331. }
  78332. currentPool.push(otherMesh);
  78333. globalLength--;
  78334. globalPool.splice(subIndex, 1);
  78335. subIndex--;
  78336. }
  78337. if (currentPool.length < 2) {
  78338. continue;
  78339. }
  78340. // Merge meshes
  78341. BABYLON.Mesh.MergeMeshes(currentPool);
  78342. }
  78343. if (updateSelectionTree != undefined) {
  78344. if (updateSelectionTree) {
  78345. scene.createOrUpdateSelectionOctree();
  78346. }
  78347. }
  78348. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  78349. scene.createOrUpdateSelectionOctree();
  78350. }
  78351. return true;
  78352. };
  78353. ;
  78354. MergeMeshesOptimization._UpdateSelectionTree = false;
  78355. return MergeMeshesOptimization;
  78356. }(SceneOptimization));
  78357. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  78358. /**
  78359. * Defines a list of options used by SceneOptimizer
  78360. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  78361. */
  78362. var SceneOptimizerOptions = /** @class */ (function () {
  78363. /**
  78364. * Creates a new list of options used by SceneOptimizer
  78365. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  78366. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  78367. */
  78368. function SceneOptimizerOptions(
  78369. /**
  78370. * Defines the target frame rate to reach (60 by default)
  78371. */
  78372. targetFrameRate,
  78373. /**
  78374. * Defines the interval between two checkes (2000ms by default)
  78375. */
  78376. trackerDuration) {
  78377. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  78378. if (trackerDuration === void 0) { trackerDuration = 2000; }
  78379. this.targetFrameRate = targetFrameRate;
  78380. this.trackerDuration = trackerDuration;
  78381. /**
  78382. * Gets the list of optimizations to apply
  78383. */
  78384. this.optimizations = new Array();
  78385. }
  78386. /**
  78387. * Add a new optimization
  78388. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  78389. * @returns the current SceneOptimizerOptions
  78390. */
  78391. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  78392. this.optimizations.push(optimization);
  78393. return this;
  78394. };
  78395. /**
  78396. * Add a new custom optimization
  78397. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  78398. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  78399. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  78400. * @returns the current SceneOptimizerOptions
  78401. */
  78402. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  78403. if (priority === void 0) { priority = 0; }
  78404. var optimization = new CustomOptimization(priority);
  78405. optimization.onApply = onApply;
  78406. optimization.onGetDescription = onGetDescription;
  78407. this.optimizations.push(optimization);
  78408. return this;
  78409. };
  78410. /**
  78411. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  78412. * @param targetFrameRate defines the target frame rate (60 by default)
  78413. * @returns a SceneOptimizerOptions object
  78414. */
  78415. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  78416. var result = new SceneOptimizerOptions(targetFrameRate);
  78417. var priority = 0;
  78418. result.addOptimization(new MergeMeshesOptimization(priority));
  78419. result.addOptimization(new ShadowsOptimization(priority));
  78420. result.addOptimization(new LensFlaresOptimization(priority));
  78421. // Next priority
  78422. priority++;
  78423. result.addOptimization(new PostProcessesOptimization(priority));
  78424. result.addOptimization(new ParticlesOptimization(priority));
  78425. // Next priority
  78426. priority++;
  78427. result.addOptimization(new TextureOptimization(priority, 1024));
  78428. return result;
  78429. };
  78430. /**
  78431. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  78432. * @param targetFrameRate defines the target frame rate (60 by default)
  78433. * @returns a SceneOptimizerOptions object
  78434. */
  78435. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  78436. var result = new SceneOptimizerOptions(targetFrameRate);
  78437. var priority = 0;
  78438. result.addOptimization(new MergeMeshesOptimization(priority));
  78439. result.addOptimization(new ShadowsOptimization(priority));
  78440. result.addOptimization(new LensFlaresOptimization(priority));
  78441. // Next priority
  78442. priority++;
  78443. result.addOptimization(new PostProcessesOptimization(priority));
  78444. result.addOptimization(new ParticlesOptimization(priority));
  78445. // Next priority
  78446. priority++;
  78447. result.addOptimization(new TextureOptimization(priority, 512));
  78448. // Next priority
  78449. priority++;
  78450. result.addOptimization(new RenderTargetsOptimization(priority));
  78451. // Next priority
  78452. priority++;
  78453. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  78454. return result;
  78455. };
  78456. /**
  78457. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  78458. * @param targetFrameRate defines the target frame rate (60 by default)
  78459. * @returns a SceneOptimizerOptions object
  78460. */
  78461. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  78462. var result = new SceneOptimizerOptions(targetFrameRate);
  78463. var priority = 0;
  78464. result.addOptimization(new MergeMeshesOptimization(priority));
  78465. result.addOptimization(new ShadowsOptimization(priority));
  78466. result.addOptimization(new LensFlaresOptimization(priority));
  78467. // Next priority
  78468. priority++;
  78469. result.addOptimization(new PostProcessesOptimization(priority));
  78470. result.addOptimization(new ParticlesOptimization(priority));
  78471. // Next priority
  78472. priority++;
  78473. result.addOptimization(new TextureOptimization(priority, 256));
  78474. // Next priority
  78475. priority++;
  78476. result.addOptimization(new RenderTargetsOptimization(priority));
  78477. // Next priority
  78478. priority++;
  78479. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  78480. return result;
  78481. };
  78482. return SceneOptimizerOptions;
  78483. }());
  78484. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  78485. /**
  78486. * Class used to run optimizations in order to reach a target frame rate
  78487. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  78488. */
  78489. var SceneOptimizer = /** @class */ (function () {
  78490. /**
  78491. * Creates a new SceneOptimizer
  78492. * @param scene defines the scene to work on
  78493. * @param options defines the options to use with the SceneOptimizer
  78494. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  78495. * @param improvementMode defines if the scene optimizer must run the maximum optimization while staying over a target frame instead of trying to reach the target framerate (false by default)
  78496. */
  78497. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  78498. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  78499. if (improvementMode === void 0) { improvementMode = false; }
  78500. var _this = this;
  78501. this._isRunning = false;
  78502. this._currentPriorityLevel = 0;
  78503. this._targetFrameRate = 60;
  78504. this._trackerDuration = 2000;
  78505. this._currentFrameRate = 0;
  78506. this._improvementMode = false;
  78507. /**
  78508. * Defines an observable called when the optimizer reaches the target frame rate
  78509. */
  78510. this.onSuccessObservable = new BABYLON.Observable();
  78511. /**
  78512. * Defines an observable called when the optimizer enables an optimization
  78513. */
  78514. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  78515. /**
  78516. * Defines an observable called when the optimizer is not able to reach the target frame rate
  78517. */
  78518. this.onFailureObservable = new BABYLON.Observable();
  78519. if (!options) {
  78520. this._options = new SceneOptimizerOptions();
  78521. }
  78522. else {
  78523. this._options = options;
  78524. }
  78525. if (this._options.targetFrameRate) {
  78526. this._targetFrameRate = this._options.targetFrameRate;
  78527. }
  78528. if (this._options.trackerDuration) {
  78529. this._trackerDuration = this._options.trackerDuration;
  78530. }
  78531. if (autoGeneratePriorities) {
  78532. var priority = 0;
  78533. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  78534. var optim = _a[_i];
  78535. optim.priority = priority++;
  78536. }
  78537. }
  78538. this._improvementMode = improvementMode;
  78539. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  78540. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  78541. _this._sceneDisposeObserver = null;
  78542. _this.dispose();
  78543. });
  78544. }
  78545. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  78546. /**
  78547. * Gets a boolean indicating if the optimizer is in improvement mode
  78548. */
  78549. get: function () {
  78550. return this._improvementMode;
  78551. },
  78552. enumerable: true,
  78553. configurable: true
  78554. });
  78555. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  78556. /**
  78557. * Gets the current priority level (0 at start)
  78558. */
  78559. get: function () {
  78560. return this._currentPriorityLevel;
  78561. },
  78562. enumerable: true,
  78563. configurable: true
  78564. });
  78565. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  78566. /**
  78567. * Gets the current frame rate checked by the SceneOptimizer
  78568. */
  78569. get: function () {
  78570. return this._currentFrameRate;
  78571. },
  78572. enumerable: true,
  78573. configurable: true
  78574. });
  78575. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  78576. /**
  78577. * Gets or sets the current target frame rate (60 by default)
  78578. */
  78579. get: function () {
  78580. return this._targetFrameRate;
  78581. },
  78582. /**
  78583. * Gets or sets the current target frame rate (60 by default)
  78584. */
  78585. set: function (value) {
  78586. this._targetFrameRate = value;
  78587. },
  78588. enumerable: true,
  78589. configurable: true
  78590. });
  78591. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  78592. /**
  78593. * Gets or sets the current interval between two checks (every 2000ms by default)
  78594. */
  78595. get: function () {
  78596. return this._trackerDuration;
  78597. },
  78598. /**
  78599. * Gets or sets the current interval between two checks (every 2000ms by default)
  78600. */
  78601. set: function (value) {
  78602. this._trackerDuration = value;
  78603. },
  78604. enumerable: true,
  78605. configurable: true
  78606. });
  78607. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  78608. /**
  78609. * Gets the list of active optimizations
  78610. */
  78611. get: function () {
  78612. return this._options.optimizations;
  78613. },
  78614. enumerable: true,
  78615. configurable: true
  78616. });
  78617. /**
  78618. * Stops the current optimizer
  78619. */
  78620. SceneOptimizer.prototype.stop = function () {
  78621. this._isRunning = false;
  78622. };
  78623. /**
  78624. * Reset the optimizer to initial step (current priority level = 0)
  78625. */
  78626. SceneOptimizer.prototype.reset = function () {
  78627. this._currentPriorityLevel = 0;
  78628. };
  78629. /**
  78630. * Start the optimizer. By default it will try to reach a specific framerate
  78631. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  78632. */
  78633. SceneOptimizer.prototype.start = function () {
  78634. var _this = this;
  78635. if (this._isRunning) {
  78636. return;
  78637. }
  78638. this._isRunning = true;
  78639. // Let's wait for the scene to be ready before running our check
  78640. this._scene.executeWhenReady(function () {
  78641. setTimeout(function () {
  78642. _this._checkCurrentState();
  78643. }, _this._trackerDuration);
  78644. });
  78645. };
  78646. SceneOptimizer.prototype._checkCurrentState = function () {
  78647. var _this = this;
  78648. if (!this._isRunning) {
  78649. return;
  78650. }
  78651. var scene = this._scene;
  78652. var options = this._options;
  78653. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  78654. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  78655. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  78656. this._isRunning = false;
  78657. this.onSuccessObservable.notifyObservers(this);
  78658. return;
  78659. }
  78660. // Apply current level of optimizations
  78661. var allDone = true;
  78662. var noOptimizationApplied = true;
  78663. for (var index = 0; index < options.optimizations.length; index++) {
  78664. var optimization = options.optimizations[index];
  78665. if (optimization.priority === this._currentPriorityLevel) {
  78666. noOptimizationApplied = false;
  78667. allDone = allDone && optimization.apply(scene, this);
  78668. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  78669. }
  78670. }
  78671. // If no optimization was applied, this is a failure :(
  78672. if (noOptimizationApplied) {
  78673. this._isRunning = false;
  78674. this.onFailureObservable.notifyObservers(this);
  78675. return;
  78676. }
  78677. // If all optimizations were done, move to next level
  78678. if (allDone) {
  78679. this._currentPriorityLevel++;
  78680. }
  78681. // Let's the system running for a specific amount of time before checking FPS
  78682. scene.executeWhenReady(function () {
  78683. setTimeout(function () {
  78684. _this._checkCurrentState();
  78685. }, _this._trackerDuration);
  78686. });
  78687. };
  78688. /**
  78689. * Release all resources
  78690. */
  78691. SceneOptimizer.prototype.dispose = function () {
  78692. this.stop();
  78693. this.onSuccessObservable.clear();
  78694. this.onFailureObservable.clear();
  78695. this.onNewOptimizationAppliedObservable.clear();
  78696. if (this._sceneDisposeObserver) {
  78697. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  78698. }
  78699. };
  78700. /**
  78701. * Helper function to create a SceneOptimizer with one single line of code
  78702. * @param scene defines the scene to work on
  78703. * @param options defines the options to use with the SceneOptimizer
  78704. * @param onSuccess defines a callback to call on success
  78705. * @param onFailure defines a callback to call on failure
  78706. * @returns the new SceneOptimizer object
  78707. */
  78708. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  78709. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  78710. if (onSuccess) {
  78711. optimizer.onSuccessObservable.add(function () {
  78712. onSuccess();
  78713. });
  78714. }
  78715. if (onFailure) {
  78716. optimizer.onFailureObservable.add(function () {
  78717. onFailure();
  78718. });
  78719. }
  78720. optimizer.start();
  78721. return optimizer;
  78722. };
  78723. return SceneOptimizer;
  78724. }());
  78725. BABYLON.SceneOptimizer = SceneOptimizer;
  78726. })(BABYLON || (BABYLON = {}));
  78727. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  78728. var BABYLON;
  78729. (function (BABYLON) {
  78730. var OutlineRenderer = /** @class */ (function () {
  78731. function OutlineRenderer(scene) {
  78732. this.zOffset = 1;
  78733. this._scene = scene;
  78734. }
  78735. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  78736. var _this = this;
  78737. if (useOverlay === void 0) { useOverlay = false; }
  78738. var scene = this._scene;
  78739. var engine = this._scene.getEngine();
  78740. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  78741. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  78742. return;
  78743. }
  78744. var mesh = subMesh.getRenderingMesh();
  78745. var material = subMesh.getMaterial();
  78746. if (!material || !scene.activeCamera) {
  78747. return;
  78748. }
  78749. engine.enableEffect(this._effect);
  78750. // Logarithmic depth
  78751. if (material.useLogarithmicDepth) {
  78752. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  78753. }
  78754. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  78755. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  78756. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  78757. // Bones
  78758. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  78759. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  78760. }
  78761. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  78762. // Alpha test
  78763. if (material && material.needAlphaTesting()) {
  78764. var alphaTexture = material.getAlphaTestTexture();
  78765. if (alphaTexture) {
  78766. this._effect.setTexture("diffuseSampler", alphaTexture);
  78767. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  78768. }
  78769. }
  78770. engine.setZOffset(-this.zOffset);
  78771. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  78772. engine.setZOffset(0);
  78773. };
  78774. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  78775. var defines = [];
  78776. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  78777. var mesh = subMesh.getMesh();
  78778. var material = subMesh.getMaterial();
  78779. if (material) {
  78780. // Alpha test
  78781. if (material.needAlphaTesting()) {
  78782. defines.push("#define ALPHATEST");
  78783. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  78784. attribs.push(BABYLON.VertexBuffer.UVKind);
  78785. defines.push("#define UV1");
  78786. }
  78787. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  78788. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  78789. defines.push("#define UV2");
  78790. }
  78791. }
  78792. //Logarithmic depth
  78793. if (material.useLogarithmicDepth) {
  78794. defines.push("#define LOGARITHMICDEPTH");
  78795. }
  78796. }
  78797. // Bones
  78798. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  78799. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  78800. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  78801. if (mesh.numBoneInfluencers > 4) {
  78802. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  78803. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  78804. }
  78805. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  78806. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  78807. }
  78808. else {
  78809. defines.push("#define NUM_BONE_INFLUENCERS 0");
  78810. }
  78811. // Instances
  78812. if (useInstances) {
  78813. defines.push("#define INSTANCES");
  78814. attribs.push("world0");
  78815. attribs.push("world1");
  78816. attribs.push("world2");
  78817. attribs.push("world3");
  78818. }
  78819. // Get correct effect
  78820. var join = defines.join("\n");
  78821. if (this._cachedDefines !== join) {
  78822. this._cachedDefines = join;
  78823. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  78824. }
  78825. return this._effect.isReady();
  78826. };
  78827. return OutlineRenderer;
  78828. }());
  78829. BABYLON.OutlineRenderer = OutlineRenderer;
  78830. })(BABYLON || (BABYLON = {}));
  78831. //# sourceMappingURL=babylon.outlineRenderer.js.map
  78832. var BABYLON;
  78833. (function (BABYLON) {
  78834. var FaceAdjacencies = /** @class */ (function () {
  78835. function FaceAdjacencies() {
  78836. this.edges = new Array();
  78837. this.edgesConnectedCount = 0;
  78838. }
  78839. return FaceAdjacencies;
  78840. }());
  78841. var EdgesRenderer = /** @class */ (function () {
  78842. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  78843. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  78844. if (epsilon === void 0) { epsilon = 0.95; }
  78845. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  78846. this.edgesWidthScalerForOrthographic = 1000.0;
  78847. this.edgesWidthScalerForPerspective = 50.0;
  78848. this._linesPositions = new Array();
  78849. this._linesNormals = new Array();
  78850. this._linesIndices = new Array();
  78851. this._buffers = {};
  78852. this._checkVerticesInsteadOfIndices = false;
  78853. this._source = source;
  78854. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  78855. this._epsilon = epsilon;
  78856. this._prepareRessources();
  78857. this._generateEdgesLines();
  78858. }
  78859. EdgesRenderer.prototype._prepareRessources = function () {
  78860. if (this._lineShader) {
  78861. return;
  78862. }
  78863. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  78864. attributes: ["position", "normal"],
  78865. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  78866. });
  78867. this._lineShader.disableDepthWrite = true;
  78868. this._lineShader.backFaceCulling = false;
  78869. };
  78870. EdgesRenderer.prototype._rebuild = function () {
  78871. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  78872. if (buffer) {
  78873. buffer._rebuild();
  78874. }
  78875. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  78876. if (buffer) {
  78877. buffer._rebuild();
  78878. }
  78879. var scene = this._source.getScene();
  78880. var engine = scene.getEngine();
  78881. this._ib = engine.createIndexBuffer(this._linesIndices);
  78882. };
  78883. EdgesRenderer.prototype.dispose = function () {
  78884. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  78885. if (buffer) {
  78886. buffer.dispose();
  78887. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  78888. }
  78889. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  78890. if (buffer) {
  78891. buffer.dispose();
  78892. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  78893. }
  78894. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  78895. this._lineShader.dispose();
  78896. };
  78897. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  78898. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  78899. return 0;
  78900. }
  78901. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  78902. return 1;
  78903. }
  78904. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  78905. return 2;
  78906. }
  78907. return -1;
  78908. };
  78909. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  78910. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  78911. return 0;
  78912. }
  78913. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  78914. return 1;
  78915. }
  78916. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  78917. return 2;
  78918. }
  78919. return -1;
  78920. };
  78921. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  78922. var needToCreateLine;
  78923. if (edge === undefined) {
  78924. needToCreateLine = true;
  78925. }
  78926. else {
  78927. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  78928. needToCreateLine = dotProduct < this._epsilon;
  78929. }
  78930. if (needToCreateLine) {
  78931. var offset = this._linesPositions.length / 3;
  78932. var normal = p0.subtract(p1);
  78933. normal.normalize();
  78934. // Positions
  78935. this._linesPositions.push(p0.x);
  78936. this._linesPositions.push(p0.y);
  78937. this._linesPositions.push(p0.z);
  78938. this._linesPositions.push(p0.x);
  78939. this._linesPositions.push(p0.y);
  78940. this._linesPositions.push(p0.z);
  78941. this._linesPositions.push(p1.x);
  78942. this._linesPositions.push(p1.y);
  78943. this._linesPositions.push(p1.z);
  78944. this._linesPositions.push(p1.x);
  78945. this._linesPositions.push(p1.y);
  78946. this._linesPositions.push(p1.z);
  78947. // Normals
  78948. this._linesNormals.push(p1.x);
  78949. this._linesNormals.push(p1.y);
  78950. this._linesNormals.push(p1.z);
  78951. this._linesNormals.push(-1);
  78952. this._linesNormals.push(p1.x);
  78953. this._linesNormals.push(p1.y);
  78954. this._linesNormals.push(p1.z);
  78955. this._linesNormals.push(1);
  78956. this._linesNormals.push(p0.x);
  78957. this._linesNormals.push(p0.y);
  78958. this._linesNormals.push(p0.z);
  78959. this._linesNormals.push(-1);
  78960. this._linesNormals.push(p0.x);
  78961. this._linesNormals.push(p0.y);
  78962. this._linesNormals.push(p0.z);
  78963. this._linesNormals.push(1);
  78964. // Indices
  78965. this._linesIndices.push(offset);
  78966. this._linesIndices.push(offset + 1);
  78967. this._linesIndices.push(offset + 2);
  78968. this._linesIndices.push(offset);
  78969. this._linesIndices.push(offset + 2);
  78970. this._linesIndices.push(offset + 3);
  78971. }
  78972. };
  78973. EdgesRenderer.prototype._generateEdgesLines = function () {
  78974. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  78975. var indices = this._source.getIndices();
  78976. if (!indices || !positions) {
  78977. return;
  78978. }
  78979. // First let's find adjacencies
  78980. var adjacencies = new Array();
  78981. var faceNormals = new Array();
  78982. var index;
  78983. var faceAdjacencies;
  78984. // Prepare faces
  78985. for (index = 0; index < indices.length; index += 3) {
  78986. faceAdjacencies = new FaceAdjacencies();
  78987. var p0Index = indices[index];
  78988. var p1Index = indices[index + 1];
  78989. var p2Index = indices[index + 2];
  78990. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  78991. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  78992. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  78993. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  78994. faceNormal.normalize();
  78995. faceNormals.push(faceNormal);
  78996. adjacencies.push(faceAdjacencies);
  78997. }
  78998. // Scan
  78999. for (index = 0; index < adjacencies.length; index++) {
  79000. faceAdjacencies = adjacencies[index];
  79001. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  79002. var otherFaceAdjacencies = adjacencies[otherIndex];
  79003. if (faceAdjacencies.edgesConnectedCount === 3) {
  79004. break;
  79005. }
  79006. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  79007. continue;
  79008. }
  79009. var otherP0 = indices[otherIndex * 3];
  79010. var otherP1 = indices[otherIndex * 3 + 1];
  79011. var otherP2 = indices[otherIndex * 3 + 2];
  79012. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  79013. var otherEdgeIndex = 0;
  79014. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  79015. continue;
  79016. }
  79017. switch (edgeIndex) {
  79018. case 0:
  79019. if (this._checkVerticesInsteadOfIndices) {
  79020. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  79021. }
  79022. else {
  79023. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  79024. }
  79025. break;
  79026. case 1:
  79027. if (this._checkVerticesInsteadOfIndices) {
  79028. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  79029. }
  79030. else {
  79031. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  79032. }
  79033. break;
  79034. case 2:
  79035. if (this._checkVerticesInsteadOfIndices) {
  79036. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  79037. }
  79038. else {
  79039. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  79040. }
  79041. break;
  79042. }
  79043. if (otherEdgeIndex === -1) {
  79044. continue;
  79045. }
  79046. faceAdjacencies.edges[edgeIndex] = otherIndex;
  79047. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  79048. faceAdjacencies.edgesConnectedCount++;
  79049. otherFaceAdjacencies.edgesConnectedCount++;
  79050. if (faceAdjacencies.edgesConnectedCount === 3) {
  79051. break;
  79052. }
  79053. }
  79054. }
  79055. }
  79056. // Create lines
  79057. for (index = 0; index < adjacencies.length; index++) {
  79058. // 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
  79059. var current = adjacencies[index];
  79060. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  79061. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  79062. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  79063. }
  79064. // Merge into a single mesh
  79065. var engine = this._source.getScene().getEngine();
  79066. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  79067. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  79068. this._ib = engine.createIndexBuffer(this._linesIndices);
  79069. this._indicesCount = this._linesIndices.length;
  79070. };
  79071. EdgesRenderer.prototype.render = function () {
  79072. var scene = this._source.getScene();
  79073. if (!this._lineShader.isReady() || !scene.activeCamera) {
  79074. return;
  79075. }
  79076. var engine = scene.getEngine();
  79077. this._lineShader._preBind();
  79078. // VBOs
  79079. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  79080. scene.resetCachedMaterial();
  79081. this._lineShader.setColor4("color", this._source.edgesColor);
  79082. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  79083. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  79084. }
  79085. else {
  79086. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  79087. }
  79088. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  79089. this._lineShader.bind(this._source.getWorldMatrix());
  79090. // Draw order
  79091. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  79092. this._lineShader.unbind();
  79093. engine.setDepthWrite(true);
  79094. };
  79095. return EdgesRenderer;
  79096. }());
  79097. BABYLON.EdgesRenderer = EdgesRenderer;
  79098. })(BABYLON || (BABYLON = {}));
  79099. //# sourceMappingURL=babylon.edgesRenderer.js.map
  79100. var BABYLON;
  79101. (function (BABYLON) {
  79102. /**
  79103. * Special Glow Blur post process only blurring the alpha channel
  79104. * It enforces keeping the most luminous color in the color channel.
  79105. */
  79106. var GlowBlurPostProcess = /** @class */ (function (_super) {
  79107. __extends(GlowBlurPostProcess, _super);
  79108. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  79109. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  79110. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  79111. _this.direction = direction;
  79112. _this.kernel = kernel;
  79113. _this.onApplyObservable.add(function (effect) {
  79114. effect.setFloat2("screenSize", _this.width, _this.height);
  79115. effect.setVector2("direction", _this.direction);
  79116. effect.setFloat("blurWidth", _this.kernel);
  79117. });
  79118. return _this;
  79119. }
  79120. return GlowBlurPostProcess;
  79121. }(BABYLON.PostProcess));
  79122. /**
  79123. * The highlight layer Helps adding a glow effect around a mesh.
  79124. *
  79125. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  79126. * glowy meshes to your scene.
  79127. *
  79128. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  79129. */
  79130. var HighlightLayer = /** @class */ (function () {
  79131. /**
  79132. * Instantiates a new highlight Layer and references it to the scene..
  79133. * @param name The name of the layer
  79134. * @param scene The scene to use the layer in
  79135. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  79136. */
  79137. function HighlightLayer(name, scene, options) {
  79138. this.name = name;
  79139. this._vertexBuffers = {};
  79140. this._mainTextureDesiredSize = { width: 0, height: 0 };
  79141. this._meshes = {};
  79142. this._maxSize = 0;
  79143. this._shouldRender = false;
  79144. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  79145. this._excludedMeshes = {};
  79146. /**
  79147. * Specifies whether or not the inner glow is ACTIVE in the layer.
  79148. */
  79149. this.innerGlow = true;
  79150. /**
  79151. * Specifies whether or not the outer glow is ACTIVE in the layer.
  79152. */
  79153. this.outerGlow = true;
  79154. /**
  79155. * Specifies wether the highlight layer is enabled or not.
  79156. */
  79157. this.isEnabled = true;
  79158. /**
  79159. * An event triggered when the highlight layer has been disposed.
  79160. * @type {BABYLON.Observable}
  79161. */
  79162. this.onDisposeObservable = new BABYLON.Observable();
  79163. /**
  79164. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  79165. * @type {BABYLON.Observable}
  79166. */
  79167. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  79168. /**
  79169. * An event triggered when the highlight layer is being blurred.
  79170. * @type {BABYLON.Observable}
  79171. */
  79172. this.onBeforeBlurObservable = new BABYLON.Observable();
  79173. /**
  79174. * An event triggered when the highlight layer has been blurred.
  79175. * @type {BABYLON.Observable}
  79176. */
  79177. this.onAfterBlurObservable = new BABYLON.Observable();
  79178. /**
  79179. * An event triggered when the glowing blurred texture is being merged in the scene.
  79180. * @type {BABYLON.Observable}
  79181. */
  79182. this.onBeforeComposeObservable = new BABYLON.Observable();
  79183. /**
  79184. * An event triggered when the glowing blurred texture has been merged in the scene.
  79185. * @type {BABYLON.Observable}
  79186. */
  79187. this.onAfterComposeObservable = new BABYLON.Observable();
  79188. /**
  79189. * An event triggered when the highlight layer changes its size.
  79190. * @type {BABYLON.Observable}
  79191. */
  79192. this.onSizeChangedObservable = new BABYLON.Observable();
  79193. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  79194. var engine = scene.getEngine();
  79195. this._engine = engine;
  79196. this._maxSize = this._engine.getCaps().maxTextureSize;
  79197. this._scene.highlightLayers.push(this);
  79198. // Warn on stencil.
  79199. if (!this._engine.isStencilEnable) {
  79200. 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 }");
  79201. }
  79202. // Adapt options
  79203. this._options = options || {
  79204. mainTextureRatio: 0.5,
  79205. blurTextureSizeRatio: 0.5,
  79206. blurHorizontalSize: 1.0,
  79207. blurVerticalSize: 1.0,
  79208. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE,
  79209. camera: null
  79210. };
  79211. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  79212. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  79213. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  79214. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  79215. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  79216. // VBO
  79217. var vertices = [];
  79218. vertices.push(1, 1);
  79219. vertices.push(-1, 1);
  79220. vertices.push(-1, -1);
  79221. vertices.push(1, -1);
  79222. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  79223. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  79224. this._createIndexBuffer();
  79225. // Effect
  79226. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  79227. // Render target
  79228. this.setMainTextureSize();
  79229. // Create Textures and post processes
  79230. this.createTextureAndPostProcesses();
  79231. }
  79232. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  79233. /**
  79234. * Gets the horizontal size of the blur.
  79235. */
  79236. get: function () {
  79237. return this._horizontalBlurPostprocess.kernel;
  79238. },
  79239. /**
  79240. * Specifies the horizontal size of the blur.
  79241. */
  79242. set: function (value) {
  79243. this._horizontalBlurPostprocess.kernel = value;
  79244. },
  79245. enumerable: true,
  79246. configurable: true
  79247. });
  79248. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  79249. /**
  79250. * Gets the vertical size of the blur.
  79251. */
  79252. get: function () {
  79253. return this._verticalBlurPostprocess.kernel;
  79254. },
  79255. /**
  79256. * Specifies the vertical size of the blur.
  79257. */
  79258. set: function (value) {
  79259. this._verticalBlurPostprocess.kernel = value;
  79260. },
  79261. enumerable: true,
  79262. configurable: true
  79263. });
  79264. Object.defineProperty(HighlightLayer.prototype, "camera", {
  79265. /**
  79266. * Gets the camera attached to the layer.
  79267. */
  79268. get: function () {
  79269. return this._options.camera;
  79270. },
  79271. enumerable: true,
  79272. configurable: true
  79273. });
  79274. HighlightLayer.prototype._createIndexBuffer = function () {
  79275. var engine = this._scene.getEngine();
  79276. // Indices
  79277. var indices = [];
  79278. indices.push(0);
  79279. indices.push(1);
  79280. indices.push(2);
  79281. indices.push(0);
  79282. indices.push(2);
  79283. indices.push(3);
  79284. this._indexBuffer = engine.createIndexBuffer(indices);
  79285. };
  79286. HighlightLayer.prototype._rebuild = function () {
  79287. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  79288. if (vb) {
  79289. vb._rebuild();
  79290. }
  79291. this._createIndexBuffer();
  79292. };
  79293. /**
  79294. * Creates the render target textures and post processes used in the highlight layer.
  79295. */
  79296. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  79297. var _this = this;
  79298. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  79299. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  79300. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  79301. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  79302. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  79303. width: this._mainTextureDesiredSize.width,
  79304. height: this._mainTextureDesiredSize.height
  79305. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  79306. this._mainTexture.activeCamera = this._options.camera;
  79307. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79308. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79309. this._mainTexture.anisotropicFilteringLevel = 1;
  79310. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  79311. this._mainTexture.renderParticles = false;
  79312. this._mainTexture.renderList = null;
  79313. this._mainTexture.ignoreCameraViewport = true;
  79314. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  79315. width: blurTextureWidth,
  79316. height: blurTextureHeight
  79317. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  79318. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79319. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79320. this._blurTexture.anisotropicFilteringLevel = 16;
  79321. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  79322. this._blurTexture.renderParticles = false;
  79323. this._blurTexture.ignoreCameraViewport = true;
  79324. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  79325. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  79326. effect.setTexture("textureSampler", _this._mainTexture);
  79327. });
  79328. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  79329. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  79330. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  79331. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  79332. });
  79333. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  79334. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  79335. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  79336. });
  79337. }
  79338. else {
  79339. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  79340. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  79341. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  79342. });
  79343. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  79344. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  79345. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  79346. });
  79347. }
  79348. this._mainTexture.onAfterUnbindObservable.add(function () {
  79349. _this.onBeforeBlurObservable.notifyObservers(_this);
  79350. var internalTexture = _this._blurTexture.getInternalTexture();
  79351. if (internalTexture) {
  79352. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], internalTexture, true);
  79353. }
  79354. _this.onAfterBlurObservable.notifyObservers(_this);
  79355. });
  79356. // Custom render function
  79357. var renderSubMesh = function (subMesh) {
  79358. if (!_this._meshes) {
  79359. return;
  79360. }
  79361. var material = subMesh.getMaterial();
  79362. var mesh = subMesh.getRenderingMesh();
  79363. var scene = _this._scene;
  79364. var engine = scene.getEngine();
  79365. if (!material) {
  79366. return;
  79367. }
  79368. // Do not block in blend mode.
  79369. if (material.needAlphaBlendingForMesh(mesh)) {
  79370. return;
  79371. }
  79372. // Culling
  79373. engine.setState(material.backFaceCulling);
  79374. // Managing instances
  79375. var batch = mesh._getInstancesRenderList(subMesh._id);
  79376. if (batch.mustReturn) {
  79377. return;
  79378. }
  79379. // Excluded Mesh
  79380. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  79381. return;
  79382. }
  79383. ;
  79384. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  79385. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  79386. var emissiveTexture = null;
  79387. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  79388. emissiveTexture = material.emissiveTexture;
  79389. }
  79390. if (_this._isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  79391. engine.enableEffect(_this._glowMapGenerationEffect);
  79392. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  79393. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  79394. if (highlightLayerMesh) {
  79395. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  79396. }
  79397. else {
  79398. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  79399. }
  79400. // Alpha test
  79401. if (material && material.needAlphaTesting()) {
  79402. var alphaTexture = material.getAlphaTestTexture();
  79403. if (alphaTexture) {
  79404. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  79405. var textureMatrix = alphaTexture.getTextureMatrix();
  79406. if (textureMatrix) {
  79407. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  79408. }
  79409. }
  79410. }
  79411. // Glow emissive only
  79412. if (emissiveTexture) {
  79413. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  79414. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  79415. }
  79416. // Bones
  79417. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  79418. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  79419. }
  79420. // Draw
  79421. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  79422. }
  79423. else {
  79424. // Need to reset refresh rate of the shadowMap
  79425. _this._mainTexture.resetRefreshCounter();
  79426. }
  79427. };
  79428. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  79429. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  79430. var index;
  79431. var engine = _this._scene.getEngine();
  79432. if (depthOnlySubMeshes.length) {
  79433. engine.setColorWrite(false);
  79434. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  79435. renderSubMesh(depthOnlySubMeshes.data[index]);
  79436. }
  79437. engine.setColorWrite(true);
  79438. }
  79439. for (index = 0; index < opaqueSubMeshes.length; index++) {
  79440. renderSubMesh(opaqueSubMeshes.data[index]);
  79441. }
  79442. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  79443. renderSubMesh(alphaTestSubMeshes.data[index]);
  79444. }
  79445. for (index = 0; index < transparentSubMeshes.length; index++) {
  79446. renderSubMesh(transparentSubMeshes.data[index]);
  79447. }
  79448. };
  79449. this._mainTexture.onClearObservable.add(function (engine) {
  79450. engine.clear(HighlightLayer.neutralColor, true, true, true);
  79451. });
  79452. };
  79453. /**
  79454. * Checks for the readiness of the element composing the layer.
  79455. * @param subMesh the mesh to check for
  79456. * @param useInstances specify wether or not to use instances to render the mesh
  79457. * @param emissiveTexture the associated emissive texture used to generate the glow
  79458. * @return true if ready otherwise, false
  79459. */
  79460. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  79461. var material = subMesh.getMaterial();
  79462. var mesh = subMesh.getRenderingMesh();
  79463. if (!material || !mesh || !this._meshes) {
  79464. return false;
  79465. }
  79466. var emissiveTexture = null;
  79467. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  79468. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  79469. emissiveTexture = material.emissiveTexture;
  79470. }
  79471. return this._isReady(subMesh, useInstances, emissiveTexture);
  79472. };
  79473. /**
  79474. * Checks for the readiness of the element composing the layer.
  79475. * @param subMesh the mesh to check for
  79476. * @param useInstances specify wether or not to use instances to render the mesh
  79477. * @param emissiveTexture the associated emissive texture used to generate the glow
  79478. * @return true if ready otherwise, false
  79479. */
  79480. HighlightLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  79481. var material = subMesh.getMaterial();
  79482. if (!material) {
  79483. return false;
  79484. }
  79485. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  79486. return false;
  79487. }
  79488. var defines = [];
  79489. var attribs = [BABYLON.VertexBuffer.PositionKind];
  79490. var mesh = subMesh.getMesh();
  79491. var uv1 = false;
  79492. var uv2 = false;
  79493. // Alpha test
  79494. if (material && material.needAlphaTesting()) {
  79495. var alphaTexture = material.getAlphaTestTexture();
  79496. if (alphaTexture) {
  79497. defines.push("#define ALPHATEST");
  79498. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  79499. alphaTexture.coordinatesIndex === 1) {
  79500. defines.push("#define DIFFUSEUV2");
  79501. uv2 = true;
  79502. }
  79503. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  79504. defines.push("#define DIFFUSEUV1");
  79505. uv1 = true;
  79506. }
  79507. }
  79508. }
  79509. // Emissive
  79510. if (emissiveTexture) {
  79511. defines.push("#define EMISSIVE");
  79512. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  79513. emissiveTexture.coordinatesIndex === 1) {
  79514. defines.push("#define EMISSIVEUV2");
  79515. uv2 = true;
  79516. }
  79517. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  79518. defines.push("#define EMISSIVEUV1");
  79519. uv1 = true;
  79520. }
  79521. }
  79522. if (uv1) {
  79523. attribs.push(BABYLON.VertexBuffer.UVKind);
  79524. defines.push("#define UV1");
  79525. }
  79526. if (uv2) {
  79527. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  79528. defines.push("#define UV2");
  79529. }
  79530. // Bones
  79531. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  79532. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  79533. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  79534. if (mesh.numBoneInfluencers > 4) {
  79535. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  79536. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  79537. }
  79538. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  79539. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  79540. }
  79541. else {
  79542. defines.push("#define NUM_BONE_INFLUENCERS 0");
  79543. }
  79544. // Instances
  79545. if (useInstances) {
  79546. defines.push("#define INSTANCES");
  79547. attribs.push("world0");
  79548. attribs.push("world1");
  79549. attribs.push("world2");
  79550. attribs.push("world3");
  79551. }
  79552. // Get correct effect
  79553. var join = defines.join("\n");
  79554. if (this._cachedDefines !== join) {
  79555. this._cachedDefines = join;
  79556. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  79557. }
  79558. return this._glowMapGenerationEffect.isReady();
  79559. };
  79560. /**
  79561. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  79562. */
  79563. HighlightLayer.prototype.render = function () {
  79564. var currentEffect = this._glowMapMergeEffect;
  79565. // Check
  79566. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  79567. return;
  79568. var engine = this._scene.getEngine();
  79569. this.onBeforeComposeObservable.notifyObservers(this);
  79570. // Render
  79571. engine.enableEffect(currentEffect);
  79572. engine.setState(false);
  79573. // Cache
  79574. var previousStencilBuffer = engine.getStencilBuffer();
  79575. var previousStencilFunction = engine.getStencilFunction();
  79576. var previousStencilMask = engine.getStencilMask();
  79577. var previousStencilOperationPass = engine.getStencilOperationPass();
  79578. var previousStencilOperationFail = engine.getStencilOperationFail();
  79579. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  79580. var previousAlphaMode = engine.getAlphaMode();
  79581. // Texture
  79582. currentEffect.setTexture("textureSampler", this._blurTexture);
  79583. // VBOs
  79584. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  79585. // Stencil operations
  79586. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  79587. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  79588. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  79589. // Draw order
  79590. engine.setAlphaMode(this._options.alphaBlendingMode);
  79591. engine.setStencilMask(0x00);
  79592. engine.setStencilBuffer(true);
  79593. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  79594. if (this.outerGlow) {
  79595. currentEffect.setFloat("offset", 0);
  79596. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  79597. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  79598. }
  79599. if (this.innerGlow) {
  79600. currentEffect.setFloat("offset", 1);
  79601. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  79602. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  79603. }
  79604. // Restore Cache
  79605. engine.setStencilFunction(previousStencilFunction);
  79606. engine.setStencilMask(previousStencilMask);
  79607. engine.setAlphaMode(previousAlphaMode);
  79608. engine.setStencilBuffer(previousStencilBuffer);
  79609. engine.setStencilOperationPass(previousStencilOperationPass);
  79610. engine.setStencilOperationFail(previousStencilOperationFail);
  79611. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  79612. engine._stencilState.reset();
  79613. this.onAfterComposeObservable.notifyObservers(this);
  79614. // Handle size changes.
  79615. var size = this._mainTexture.getSize();
  79616. this.setMainTextureSize();
  79617. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  79618. // Recreate RTT and post processes on size change.
  79619. this.onSizeChangedObservable.notifyObservers(this);
  79620. this.disposeTextureAndPostProcesses();
  79621. this.createTextureAndPostProcesses();
  79622. }
  79623. };
  79624. /**
  79625. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  79626. * @param mesh The mesh to exclude from the highlight layer
  79627. */
  79628. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  79629. if (!this._excludedMeshes) {
  79630. return;
  79631. }
  79632. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  79633. if (!meshExcluded) {
  79634. this._excludedMeshes[mesh.uniqueId] = {
  79635. mesh: mesh,
  79636. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  79637. mesh.getEngine().setStencilBuffer(false);
  79638. }),
  79639. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  79640. mesh.getEngine().setStencilBuffer(true);
  79641. }),
  79642. };
  79643. }
  79644. };
  79645. /**
  79646. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  79647. * @param mesh The mesh to highlight
  79648. */
  79649. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  79650. if (!this._excludedMeshes) {
  79651. return;
  79652. }
  79653. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  79654. if (meshExcluded) {
  79655. if (meshExcluded.beforeRender) {
  79656. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  79657. }
  79658. if (meshExcluded.afterRender) {
  79659. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  79660. }
  79661. }
  79662. this._excludedMeshes[mesh.uniqueId] = null;
  79663. };
  79664. /**
  79665. * Determine if a given mesh will be highlighted by the current HighlightLayer
  79666. * @param mesh mesh to test
  79667. * @returns true if the mesh will be highlighted by the current HighlightLayer
  79668. */
  79669. HighlightLayer.prototype.hasMesh = function (mesh) {
  79670. if (!this._meshes) {
  79671. return false;
  79672. }
  79673. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  79674. };
  79675. /**
  79676. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  79677. * @param mesh The mesh to highlight
  79678. * @param color The color of the highlight
  79679. * @param glowEmissiveOnly Extract the glow from the emissive texture
  79680. */
  79681. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  79682. var _this = this;
  79683. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  79684. if (!this._meshes) {
  79685. return;
  79686. }
  79687. var meshHighlight = this._meshes[mesh.uniqueId];
  79688. if (meshHighlight) {
  79689. meshHighlight.color = color;
  79690. }
  79691. else {
  79692. this._meshes[mesh.uniqueId] = {
  79693. mesh: mesh,
  79694. color: color,
  79695. // Lambda required for capture due to Observable this context
  79696. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  79697. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  79698. _this.defaultStencilReference(mesh);
  79699. }
  79700. else {
  79701. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  79702. }
  79703. }),
  79704. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  79705. glowEmissiveOnly: glowEmissiveOnly
  79706. };
  79707. }
  79708. this._shouldRender = true;
  79709. };
  79710. /**
  79711. * Remove a mesh from the highlight layer in order to make it stop glowing.
  79712. * @param mesh The mesh to highlight
  79713. */
  79714. HighlightLayer.prototype.removeMesh = function (mesh) {
  79715. if (!this._meshes) {
  79716. return;
  79717. }
  79718. var meshHighlight = this._meshes[mesh.uniqueId];
  79719. if (meshHighlight) {
  79720. if (meshHighlight.observerHighlight) {
  79721. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  79722. }
  79723. if (meshHighlight.observerDefault) {
  79724. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  79725. }
  79726. delete this._meshes[mesh.uniqueId];
  79727. }
  79728. this._shouldRender = false;
  79729. for (var meshHighlightToCheck in this._meshes) {
  79730. if (this._meshes[meshHighlightToCheck]) {
  79731. this._shouldRender = true;
  79732. break;
  79733. }
  79734. }
  79735. };
  79736. /**
  79737. * Returns true if the layer contains information to display, otherwise false.
  79738. */
  79739. HighlightLayer.prototype.shouldRender = function () {
  79740. return this.isEnabled && this._shouldRender;
  79741. };
  79742. /**
  79743. * Sets the main texture desired size which is the closest power of two
  79744. * of the engine canvas size.
  79745. */
  79746. HighlightLayer.prototype.setMainTextureSize = function () {
  79747. if (this._options.mainTextureFixedSize) {
  79748. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  79749. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  79750. }
  79751. else {
  79752. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio;
  79753. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio;
  79754. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  79755. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  79756. }
  79757. };
  79758. /**
  79759. * Force the stencil to the normal expected value for none glowing parts
  79760. */
  79761. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  79762. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  79763. };
  79764. /**
  79765. * Dispose only the render target textures and post process.
  79766. */
  79767. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  79768. this._blurTexture.dispose();
  79769. this._mainTexture.dispose();
  79770. this._downSamplePostprocess.dispose();
  79771. this._horizontalBlurPostprocess.dispose();
  79772. this._verticalBlurPostprocess.dispose();
  79773. };
  79774. /**
  79775. * Dispose the highlight layer and free resources.
  79776. */
  79777. HighlightLayer.prototype.dispose = function () {
  79778. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  79779. if (vertexBuffer) {
  79780. vertexBuffer.dispose();
  79781. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  79782. }
  79783. if (this._indexBuffer) {
  79784. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  79785. this._indexBuffer = null;
  79786. }
  79787. // Clean textures and post processes
  79788. this.disposeTextureAndPostProcesses();
  79789. if (this._meshes) {
  79790. // Clean mesh references
  79791. for (var id in this._meshes) {
  79792. var meshHighlight = this._meshes[id];
  79793. if (meshHighlight && meshHighlight.mesh) {
  79794. if (meshHighlight.observerHighlight) {
  79795. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  79796. }
  79797. if (meshHighlight.observerDefault) {
  79798. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  79799. }
  79800. }
  79801. }
  79802. this._meshes = null;
  79803. }
  79804. if (this._excludedMeshes) {
  79805. for (var id in this._excludedMeshes) {
  79806. var meshHighlight = this._excludedMeshes[id];
  79807. if (meshHighlight) {
  79808. if (meshHighlight.beforeRender) {
  79809. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  79810. }
  79811. if (meshHighlight.afterRender) {
  79812. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  79813. }
  79814. }
  79815. }
  79816. this._excludedMeshes = null;
  79817. }
  79818. // Remove from scene
  79819. var index = this._scene.highlightLayers.indexOf(this, 0);
  79820. if (index > -1) {
  79821. this._scene.highlightLayers.splice(index, 1);
  79822. }
  79823. // Callback
  79824. this.onDisposeObservable.notifyObservers(this);
  79825. this.onDisposeObservable.clear();
  79826. this.onBeforeRenderMainTextureObservable.clear();
  79827. this.onBeforeBlurObservable.clear();
  79828. this.onBeforeComposeObservable.clear();
  79829. this.onAfterComposeObservable.clear();
  79830. this.onSizeChangedObservable.clear();
  79831. };
  79832. /**
  79833. * The neutral color used during the preparation of the glow effect.
  79834. * This is black by default as the blend operation is a blend operation.
  79835. */
  79836. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  79837. /**
  79838. * Stencil value used for glowing meshes.
  79839. */
  79840. HighlightLayer.glowingMeshStencilReference = 0x02;
  79841. /**
  79842. * Stencil value used for the other meshes in the scene.
  79843. */
  79844. HighlightLayer.normalMeshStencilReference = 0x01;
  79845. return HighlightLayer;
  79846. }());
  79847. BABYLON.HighlightLayer = HighlightLayer;
  79848. })(BABYLON || (BABYLON = {}));
  79849. //# sourceMappingURL=babylon.highlightlayer.js.map
  79850. var BABYLON;
  79851. (function (BABYLON) {
  79852. /**
  79853. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  79854. */
  79855. var AssetTaskState;
  79856. (function (AssetTaskState) {
  79857. /**
  79858. * Initialization
  79859. */
  79860. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  79861. /**
  79862. * Running
  79863. */
  79864. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  79865. /**
  79866. * Done
  79867. */
  79868. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  79869. /**
  79870. * Error
  79871. */
  79872. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  79873. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  79874. /**
  79875. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  79876. */
  79877. var AbstractAssetTask = /** @class */ (function () {
  79878. /**
  79879. * Creates a new {BABYLON.AssetsManager}
  79880. * @param name defines the name of the task
  79881. */
  79882. function AbstractAssetTask(
  79883. /**
  79884. * Task name
  79885. */ name) {
  79886. this.name = name;
  79887. this._isCompleted = false;
  79888. this._taskState = AssetTaskState.INIT;
  79889. }
  79890. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  79891. /**
  79892. * Get if the task is completed
  79893. */
  79894. get: function () {
  79895. return this._isCompleted;
  79896. },
  79897. enumerable: true,
  79898. configurable: true
  79899. });
  79900. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  79901. /**
  79902. * Gets the current state of the task
  79903. */
  79904. get: function () {
  79905. return this._taskState;
  79906. },
  79907. enumerable: true,
  79908. configurable: true
  79909. });
  79910. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  79911. /**
  79912. * Gets the current error object (if task is in error)
  79913. */
  79914. get: function () {
  79915. return this._errorObject;
  79916. },
  79917. enumerable: true,
  79918. configurable: true
  79919. });
  79920. /**
  79921. * Internal only
  79922. * @ignore
  79923. */
  79924. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  79925. if (this._errorObject) {
  79926. return;
  79927. }
  79928. this._errorObject = {
  79929. message: message,
  79930. exception: exception
  79931. };
  79932. };
  79933. /**
  79934. * Execute the current task
  79935. * @param scene defines the scene where you want your assets to be loaded
  79936. * @param onSuccess is a callback called when the task is successfully executed
  79937. * @param onError is a callback called if an error occurs
  79938. */
  79939. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  79940. var _this = this;
  79941. this._taskState = AssetTaskState.RUNNING;
  79942. this.runTask(scene, function () {
  79943. _this.onDoneCallback(onSuccess, onError);
  79944. }, function (msg, exception) {
  79945. _this.onErrorCallback(onError, msg, exception);
  79946. });
  79947. };
  79948. /**
  79949. * Execute the current task
  79950. * @param scene defines the scene where you want your assets to be loaded
  79951. * @param onSuccess is a callback called when the task is successfully executed
  79952. * @param onError is a callback called if an error occurs
  79953. */
  79954. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  79955. throw new Error("runTask is not implemented");
  79956. };
  79957. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  79958. this._taskState = AssetTaskState.ERROR;
  79959. this._errorObject = {
  79960. message: message,
  79961. exception: exception
  79962. };
  79963. if (this.onError) {
  79964. this.onError(this, message, exception);
  79965. }
  79966. onError();
  79967. };
  79968. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  79969. try {
  79970. this._taskState = AssetTaskState.DONE;
  79971. this._isCompleted = true;
  79972. if (this.onSuccess) {
  79973. this.onSuccess(this);
  79974. }
  79975. onSuccess();
  79976. }
  79977. catch (e) {
  79978. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  79979. }
  79980. };
  79981. return AbstractAssetTask;
  79982. }());
  79983. BABYLON.AbstractAssetTask = AbstractAssetTask;
  79984. /**
  79985. * Class used to share progress information about assets loading
  79986. */
  79987. var AssetsProgressEvent = /** @class */ (function () {
  79988. /**
  79989. * Creates a {BABYLON.AssetsProgressEvent}
  79990. * @param remainingCount defines the number of remaining tasks to process
  79991. * @param totalCount defines the total number of tasks
  79992. * @param task defines the task that was just processed
  79993. */
  79994. function AssetsProgressEvent(remainingCount, totalCount, task) {
  79995. this.remainingCount = remainingCount;
  79996. this.totalCount = totalCount;
  79997. this.task = task;
  79998. }
  79999. return AssetsProgressEvent;
  80000. }());
  80001. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  80002. /**
  80003. * Define a task used by {BABYLON.AssetsManager} to load meshes
  80004. */
  80005. var MeshAssetTask = /** @class */ (function (_super) {
  80006. __extends(MeshAssetTask, _super);
  80007. /**
  80008. * Creates a new {BABYLON.MeshAssetTask}
  80009. * @param name defines the name of the task
  80010. * @param meshesNames defines the list of mesh's names you want to load
  80011. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  80012. * @param sceneFilename defines the filename of the scene to load from
  80013. */
  80014. function MeshAssetTask(
  80015. /**
  80016. * Defines the name of the task
  80017. */
  80018. name,
  80019. /**
  80020. * Defines the list of mesh's names you want to load
  80021. */
  80022. meshesNames,
  80023. /**
  80024. * Defines the root url to use as a base to load your meshes and associated resources
  80025. */
  80026. rootUrl,
  80027. /**
  80028. * Defines the filename of the scene to load from
  80029. */
  80030. sceneFilename) {
  80031. var _this = _super.call(this, name) || this;
  80032. _this.name = name;
  80033. _this.meshesNames = meshesNames;
  80034. _this.rootUrl = rootUrl;
  80035. _this.sceneFilename = sceneFilename;
  80036. return _this;
  80037. }
  80038. /**
  80039. * Execute the current task
  80040. * @param scene defines the scene where you want your assets to be loaded
  80041. * @param onSuccess is a callback called when the task is successfully executed
  80042. * @param onError is a callback called if an error occurs
  80043. */
  80044. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  80045. var _this = this;
  80046. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  80047. _this.loadedMeshes = meshes;
  80048. _this.loadedParticleSystems = particleSystems;
  80049. _this.loadedSkeletons = skeletons;
  80050. onSuccess();
  80051. }, null, function (scene, message, exception) {
  80052. onError(message, exception);
  80053. });
  80054. };
  80055. return MeshAssetTask;
  80056. }(AbstractAssetTask));
  80057. BABYLON.MeshAssetTask = MeshAssetTask;
  80058. /**
  80059. * Define a task used by {BABYLON.AssetsManager} to load text content
  80060. */
  80061. var TextFileAssetTask = /** @class */ (function (_super) {
  80062. __extends(TextFileAssetTask, _super);
  80063. /**
  80064. * Creates a new TextFileAssetTask object
  80065. * @param name defines the name of the task
  80066. * @param url defines the location of the file to load
  80067. */
  80068. function TextFileAssetTask(
  80069. /**
  80070. * Defines the name of the task
  80071. */
  80072. name,
  80073. /**
  80074. * Defines the location of the file to load
  80075. */
  80076. url) {
  80077. var _this = _super.call(this, name) || this;
  80078. _this.name = name;
  80079. _this.url = url;
  80080. return _this;
  80081. }
  80082. /**
  80083. * Execute the current task
  80084. * @param scene defines the scene where you want your assets to be loaded
  80085. * @param onSuccess is a callback called when the task is successfully executed
  80086. * @param onError is a callback called if an error occurs
  80087. */
  80088. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  80089. var _this = this;
  80090. scene._loadFile(this.url, function (data) {
  80091. _this.text = data;
  80092. onSuccess();
  80093. }, undefined, false, true, function (request, exception) {
  80094. if (request) {
  80095. onError(request.status + " " + request.statusText, exception);
  80096. }
  80097. });
  80098. };
  80099. return TextFileAssetTask;
  80100. }(AbstractAssetTask));
  80101. BABYLON.TextFileAssetTask = TextFileAssetTask;
  80102. /**
  80103. * Define a task used by {BABYLON.AssetsManager} to load binary data
  80104. */
  80105. var BinaryFileAssetTask = /** @class */ (function (_super) {
  80106. __extends(BinaryFileAssetTask, _super);
  80107. /**
  80108. * Creates a new BinaryFileAssetTask object
  80109. * @param name defines the name of the new task
  80110. * @param url defines the location of the file to load
  80111. */
  80112. function BinaryFileAssetTask(
  80113. /**
  80114. * Defines the name of the task
  80115. */
  80116. name,
  80117. /**
  80118. * Defines the location of the file to load
  80119. */
  80120. url) {
  80121. var _this = _super.call(this, name) || this;
  80122. _this.name = name;
  80123. _this.url = url;
  80124. return _this;
  80125. }
  80126. /**
  80127. * Execute the current task
  80128. * @param scene defines the scene where you want your assets to be loaded
  80129. * @param onSuccess is a callback called when the task is successfully executed
  80130. * @param onError is a callback called if an error occurs
  80131. */
  80132. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  80133. var _this = this;
  80134. scene._loadFile(this.url, function (data) {
  80135. _this.data = data;
  80136. onSuccess();
  80137. }, undefined, true, true, function (request, exception) {
  80138. if (request) {
  80139. onError(request.status + " " + request.statusText, exception);
  80140. }
  80141. });
  80142. };
  80143. return BinaryFileAssetTask;
  80144. }(AbstractAssetTask));
  80145. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  80146. /**
  80147. * Define a task used by {BABYLON.AssetsManager} to load images
  80148. */
  80149. var ImageAssetTask = /** @class */ (function (_super) {
  80150. __extends(ImageAssetTask, _super);
  80151. /**
  80152. * Creates a new ImageAssetTask
  80153. * @param name defines the name of the task
  80154. * @param url defines the location of the image to load
  80155. */
  80156. function ImageAssetTask(
  80157. /**
  80158. * Defines the name of the task
  80159. */
  80160. name,
  80161. /**
  80162. * Defines the location of the image to load
  80163. */
  80164. url) {
  80165. var _this = _super.call(this, name) || this;
  80166. _this.name = name;
  80167. _this.url = url;
  80168. return _this;
  80169. }
  80170. /**
  80171. * Execute the current task
  80172. * @param scene defines the scene where you want your assets to be loaded
  80173. * @param onSuccess is a callback called when the task is successfully executed
  80174. * @param onError is a callback called if an error occurs
  80175. */
  80176. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  80177. var _this = this;
  80178. var img = new Image();
  80179. BABYLON.Tools.SetCorsBehavior(this.url, img);
  80180. img.onload = function () {
  80181. _this.image = img;
  80182. onSuccess();
  80183. };
  80184. img.onerror = function (err) {
  80185. onError("Error loading image", err);
  80186. };
  80187. img.src = this.url;
  80188. };
  80189. return ImageAssetTask;
  80190. }(AbstractAssetTask));
  80191. BABYLON.ImageAssetTask = ImageAssetTask;
  80192. /**
  80193. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  80194. */
  80195. var TextureAssetTask = /** @class */ (function (_super) {
  80196. __extends(TextureAssetTask, _super);
  80197. /**
  80198. * Creates a new TextureAssetTask object
  80199. * @param name defines the name of the task
  80200. * @param url defines the location of the file to load
  80201. * @param noMipmap defines if mipmap should not be generated (default is false)
  80202. * @param invertY defines if texture must be inverted on Y axis (default is false)
  80203. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  80204. */
  80205. function TextureAssetTask(
  80206. /**
  80207. * Defines the name of the task
  80208. */
  80209. name,
  80210. /**
  80211. * Defines the location of the file to load
  80212. */
  80213. url,
  80214. /**
  80215. * Defines if mipmap should not be generated (default is false)
  80216. */
  80217. noMipmap,
  80218. /**
  80219. * Defines if texture must be inverted on Y axis (default is false)
  80220. */
  80221. invertY,
  80222. /**
  80223. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  80224. */
  80225. samplingMode) {
  80226. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  80227. var _this = _super.call(this, name) || this;
  80228. _this.name = name;
  80229. _this.url = url;
  80230. _this.noMipmap = noMipmap;
  80231. _this.invertY = invertY;
  80232. _this.samplingMode = samplingMode;
  80233. return _this;
  80234. }
  80235. /**
  80236. * Execute the current task
  80237. * @param scene defines the scene where you want your assets to be loaded
  80238. * @param onSuccess is a callback called when the task is successfully executed
  80239. * @param onError is a callback called if an error occurs
  80240. */
  80241. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  80242. var onload = function () {
  80243. onSuccess();
  80244. };
  80245. var onerror = function (message, exception) {
  80246. onError(message, exception);
  80247. };
  80248. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  80249. };
  80250. return TextureAssetTask;
  80251. }(AbstractAssetTask));
  80252. BABYLON.TextureAssetTask = TextureAssetTask;
  80253. /**
  80254. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  80255. */
  80256. var CubeTextureAssetTask = /** @class */ (function (_super) {
  80257. __extends(CubeTextureAssetTask, _super);
  80258. /**
  80259. * Creates a new CubeTextureAssetTask
  80260. * @param name defines the name of the task
  80261. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  80262. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  80263. * @param noMipmap defines if mipmaps should not be generated (default is false)
  80264. * @param files defines the explicit list of files (undefined by default)
  80265. */
  80266. function CubeTextureAssetTask(
  80267. /**
  80268. * Defines the name of the task
  80269. */
  80270. name,
  80271. /**
  80272. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  80273. */
  80274. url,
  80275. /**
  80276. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  80277. */
  80278. extensions,
  80279. /**
  80280. * Defines if mipmaps should not be generated (default is false)
  80281. */
  80282. noMipmap,
  80283. /**
  80284. * Defines the explicit list of files (undefined by default)
  80285. */
  80286. files) {
  80287. var _this = _super.call(this, name) || this;
  80288. _this.name = name;
  80289. _this.url = url;
  80290. _this.extensions = extensions;
  80291. _this.noMipmap = noMipmap;
  80292. _this.files = files;
  80293. return _this;
  80294. }
  80295. /**
  80296. * Execute the current task
  80297. * @param scene defines the scene where you want your assets to be loaded
  80298. * @param onSuccess is a callback called when the task is successfully executed
  80299. * @param onError is a callback called if an error occurs
  80300. */
  80301. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  80302. var onload = function () {
  80303. onSuccess();
  80304. };
  80305. var onerror = function (message, exception) {
  80306. onError(message, exception);
  80307. };
  80308. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  80309. };
  80310. return CubeTextureAssetTask;
  80311. }(AbstractAssetTask));
  80312. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  80313. /**
  80314. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  80315. */
  80316. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  80317. __extends(HDRCubeTextureAssetTask, _super);
  80318. /**
  80319. * Creates a new HDRCubeTextureAssetTask object
  80320. * @param name defines the name of the task
  80321. * @param url defines the location of the file to load
  80322. * @param size defines the desired size (the more it increases the longer the generation will be) If the size is omitted this implies you are using a preprocessed cubemap.
  80323. * @param noMipmap defines if mipmaps should not be generated (default is false)
  80324. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  80325. * @param useInGammaSpace specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)
  80326. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  80327. */
  80328. function HDRCubeTextureAssetTask(
  80329. /**
  80330. * Defines the name of the task
  80331. */
  80332. name,
  80333. /**
  80334. * Defines the location of the file to load
  80335. */
  80336. url,
  80337. /**
  80338. * Defines the desired size (the more it increases the longer the generation will be) If the size is omitted this implies you are using a preprocessed cubemap.
  80339. */
  80340. size,
  80341. /**
  80342. * Defines if mipmaps should not be generated (default is false)
  80343. */
  80344. noMipmap,
  80345. /**
  80346. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  80347. */
  80348. generateHarmonics,
  80349. /**
  80350. * Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)
  80351. */
  80352. useInGammaSpace,
  80353. /**
  80354. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  80355. */
  80356. usePMREMGenerator) {
  80357. if (noMipmap === void 0) { noMipmap = false; }
  80358. if (generateHarmonics === void 0) { generateHarmonics = true; }
  80359. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  80360. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  80361. var _this = _super.call(this, name) || this;
  80362. _this.name = name;
  80363. _this.url = url;
  80364. _this.size = size;
  80365. _this.noMipmap = noMipmap;
  80366. _this.generateHarmonics = generateHarmonics;
  80367. _this.useInGammaSpace = useInGammaSpace;
  80368. _this.usePMREMGenerator = usePMREMGenerator;
  80369. return _this;
  80370. }
  80371. /**
  80372. * Execute the current task
  80373. * @param scene defines the scene where you want your assets to be loaded
  80374. * @param onSuccess is a callback called when the task is successfully executed
  80375. * @param onError is a callback called if an error occurs
  80376. */
  80377. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  80378. var onload = function () {
  80379. onSuccess();
  80380. };
  80381. var onerror = function (message, exception) {
  80382. onError(message, exception);
  80383. };
  80384. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  80385. };
  80386. return HDRCubeTextureAssetTask;
  80387. }(AbstractAssetTask));
  80388. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  80389. /**
  80390. * This class can be used to easily import assets into a scene
  80391. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  80392. */
  80393. var AssetsManager = /** @class */ (function () {
  80394. /**
  80395. * Creates a new AssetsManager
  80396. * @param scene defines the scene to work on
  80397. */
  80398. function AssetsManager(scene) {
  80399. this._isLoading = false;
  80400. this._tasks = new Array();
  80401. this._waitingTasksCount = 0;
  80402. this._totalTasksCount = 0;
  80403. /**
  80404. * Observable called when all tasks are processed
  80405. */
  80406. this.onTaskSuccessObservable = new BABYLON.Observable();
  80407. /**
  80408. * Observable called when a task had an error
  80409. */
  80410. this.onTaskErrorObservable = new BABYLON.Observable();
  80411. /**
  80412. * Observable called when a task is successful
  80413. */
  80414. this.onTasksDoneObservable = new BABYLON.Observable();
  80415. /**
  80416. * Observable called when a task is done (whatever the result is)
  80417. */
  80418. this.onProgressObservable = new BABYLON.Observable();
  80419. /**
  80420. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  80421. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  80422. */
  80423. this.useDefaultLoadingScreen = true;
  80424. this._scene = scene;
  80425. }
  80426. /**
  80427. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  80428. * @param taskName defines the name of the new task
  80429. * @param meshesNames defines the name of meshes to load
  80430. * @param rootUrl defines the root url to use to locate files
  80431. * @param sceneFilename defines the filename of the scene file
  80432. * @returns a new {BABYLON.MeshAssetTask} object
  80433. */
  80434. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  80435. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  80436. this._tasks.push(task);
  80437. return task;
  80438. };
  80439. /**
  80440. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  80441. * @param taskName defines the name of the new task
  80442. * @param url defines the url of the file to load
  80443. * @returns a new {BABYLON.TextFileAssetTask} object
  80444. */
  80445. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  80446. var task = new TextFileAssetTask(taskName, url);
  80447. this._tasks.push(task);
  80448. return task;
  80449. };
  80450. /**
  80451. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  80452. * @param taskName defines the name of the new task
  80453. * @param url defines the url of the file to load
  80454. * @returns a new {BABYLON.BinaryFileAssetTask} object
  80455. */
  80456. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  80457. var task = new BinaryFileAssetTask(taskName, url);
  80458. this._tasks.push(task);
  80459. return task;
  80460. };
  80461. /**
  80462. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  80463. * @param taskName defines the name of the new task
  80464. * @param url defines the url of the file to load
  80465. * @returns a new {BABYLON.ImageAssetTask} object
  80466. */
  80467. AssetsManager.prototype.addImageTask = function (taskName, url) {
  80468. var task = new ImageAssetTask(taskName, url);
  80469. this._tasks.push(task);
  80470. return task;
  80471. };
  80472. /**
  80473. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  80474. * @param taskName defines the name of the new task
  80475. * @param url defines the url of the file to load
  80476. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  80477. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  80478. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  80479. * @returns a new {BABYLON.TextureAssetTask} object
  80480. */
  80481. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  80482. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  80483. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  80484. this._tasks.push(task);
  80485. return task;
  80486. };
  80487. /**
  80488. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  80489. * @param taskName defines the name of the new task
  80490. * @param url defines the url of the file to load
  80491. * @param extensions defines the extension to use to load the cube map (can be null)
  80492. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  80493. * @param files defines the list of files to load (can be null)
  80494. * @returns a new {BABYLON.CubeTextureAssetTask} object
  80495. */
  80496. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  80497. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  80498. this._tasks.push(task);
  80499. return task;
  80500. };
  80501. /**
  80502. *
  80503. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  80504. * @param taskName defines the name of the new task
  80505. * @param url defines the url of the file to load
  80506. * @param size defines the size you want for the cubemap (can be null)
  80507. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  80508. * @param generateHarmonics defines if you want to automatically generate (true by default)
  80509. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  80510. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  80511. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  80512. */
  80513. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  80514. if (noMipmap === void 0) { noMipmap = false; }
  80515. if (generateHarmonics === void 0) { generateHarmonics = true; }
  80516. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  80517. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  80518. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  80519. this._tasks.push(task);
  80520. return task;
  80521. };
  80522. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  80523. var _this = this;
  80524. this._waitingTasksCount--;
  80525. try {
  80526. if (task.taskState === AssetTaskState.DONE) {
  80527. // Let's remove successfull tasks
  80528. BABYLON.Tools.SetImmediate(function () {
  80529. var index = _this._tasks.indexOf(task);
  80530. if (index > -1) {
  80531. _this._tasks.splice(index, 1);
  80532. }
  80533. });
  80534. }
  80535. if (this.onProgress) {
  80536. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  80537. }
  80538. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  80539. }
  80540. catch (e) {
  80541. BABYLON.Tools.Error("Error running progress callbacks.");
  80542. console.log(e);
  80543. }
  80544. if (this._waitingTasksCount === 0) {
  80545. try {
  80546. if (this.onFinish) {
  80547. this.onFinish(this._tasks);
  80548. }
  80549. this.onTasksDoneObservable.notifyObservers(this._tasks);
  80550. }
  80551. catch (e) {
  80552. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  80553. console.log(e);
  80554. }
  80555. this._isLoading = false;
  80556. this._scene.getEngine().hideLoadingUI();
  80557. }
  80558. };
  80559. AssetsManager.prototype._runTask = function (task) {
  80560. var _this = this;
  80561. var done = function () {
  80562. try {
  80563. if (_this.onTaskSuccess) {
  80564. _this.onTaskSuccess(task);
  80565. }
  80566. _this.onTaskSuccessObservable.notifyObservers(task);
  80567. _this._decreaseWaitingTasksCount(task);
  80568. }
  80569. catch (e) {
  80570. error("Error executing task success callbacks", e);
  80571. }
  80572. };
  80573. var error = function (message, exception) {
  80574. task._setErrorObject(message, exception);
  80575. if (_this.onTaskError) {
  80576. _this.onTaskError(task);
  80577. }
  80578. _this.onTaskErrorObservable.notifyObservers(task);
  80579. _this._decreaseWaitingTasksCount(task);
  80580. };
  80581. task.run(this._scene, done, error);
  80582. };
  80583. /**
  80584. * Reset the {BABYLON.AssetsManager} and remove all tasks
  80585. * @return the current instance of the {BABYLON.AssetsManager}
  80586. */
  80587. AssetsManager.prototype.reset = function () {
  80588. this._isLoading = false;
  80589. this._tasks = new Array();
  80590. return this;
  80591. };
  80592. /**
  80593. * Start the loading process
  80594. * @return the current instance of the {BABYLON.AssetsManager}
  80595. */
  80596. AssetsManager.prototype.load = function () {
  80597. if (this._isLoading) {
  80598. return this;
  80599. }
  80600. this._isLoading = true;
  80601. this._waitingTasksCount = this._tasks.length;
  80602. this._totalTasksCount = this._tasks.length;
  80603. if (this._waitingTasksCount === 0) {
  80604. if (this.onFinish) {
  80605. this.onFinish(this._tasks);
  80606. }
  80607. this.onTasksDoneObservable.notifyObservers(this._tasks);
  80608. return this;
  80609. }
  80610. if (this.useDefaultLoadingScreen) {
  80611. this._scene.getEngine().displayLoadingUI();
  80612. }
  80613. for (var index = 0; index < this._tasks.length; index++) {
  80614. var task = this._tasks[index];
  80615. this._runTask(task);
  80616. }
  80617. return this;
  80618. };
  80619. return AssetsManager;
  80620. }());
  80621. BABYLON.AssetsManager = AssetsManager;
  80622. })(BABYLON || (BABYLON = {}));
  80623. //# sourceMappingURL=babylon.assetsManager.js.map
  80624. var BABYLON;
  80625. (function (BABYLON) {
  80626. var serializedGeometries = [];
  80627. var serializeGeometry = function (geometry, serializationGeometries) {
  80628. if (serializedGeometries[geometry.id]) {
  80629. return;
  80630. }
  80631. if (geometry.doNotSerialize) {
  80632. return;
  80633. }
  80634. if (geometry instanceof BABYLON.BoxGeometry) {
  80635. serializationGeometries.boxes.push(geometry.serialize());
  80636. }
  80637. else if (geometry instanceof BABYLON.SphereGeometry) {
  80638. serializationGeometries.spheres.push(geometry.serialize());
  80639. }
  80640. else if (geometry instanceof BABYLON.CylinderGeometry) {
  80641. serializationGeometries.cylinders.push(geometry.serialize());
  80642. }
  80643. else if (geometry instanceof BABYLON.TorusGeometry) {
  80644. serializationGeometries.toruses.push(geometry.serialize());
  80645. }
  80646. else if (geometry instanceof BABYLON.GroundGeometry) {
  80647. serializationGeometries.grounds.push(geometry.serialize());
  80648. }
  80649. else if (geometry instanceof BABYLON.Plane) {
  80650. serializationGeometries.planes.push(geometry.serialize());
  80651. }
  80652. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  80653. serializationGeometries.torusKnots.push(geometry.serialize());
  80654. }
  80655. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  80656. throw new Error("Unknown primitive type");
  80657. }
  80658. else {
  80659. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  80660. }
  80661. serializedGeometries[geometry.id] = true;
  80662. };
  80663. var serializeMesh = function (mesh, serializationScene) {
  80664. var serializationObject = {};
  80665. // Geometry
  80666. var geometry = mesh._geometry;
  80667. if (geometry) {
  80668. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  80669. // 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
  80670. serializeGeometry(geometry, serializationScene.geometries);
  80671. }
  80672. }
  80673. // Custom
  80674. if (mesh.serialize) {
  80675. mesh.serialize(serializationObject);
  80676. }
  80677. return serializationObject;
  80678. };
  80679. var finalizeSingleMesh = function (mesh, serializationObject) {
  80680. //only works if the mesh is already loaded
  80681. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  80682. //serialize material
  80683. if (mesh.material) {
  80684. if (mesh.material instanceof BABYLON.StandardMaterial) {
  80685. serializationObject.materials = serializationObject.materials || [];
  80686. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  80687. serializationObject.materials.push(mesh.material.serialize());
  80688. }
  80689. }
  80690. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  80691. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  80692. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  80693. serializationObject.multiMaterials.push(mesh.material.serialize());
  80694. }
  80695. }
  80696. }
  80697. //serialize geometry
  80698. var geometry = mesh._geometry;
  80699. if (geometry) {
  80700. if (!serializationObject.geometries) {
  80701. serializationObject.geometries = {};
  80702. serializationObject.geometries.boxes = [];
  80703. serializationObject.geometries.spheres = [];
  80704. serializationObject.geometries.cylinders = [];
  80705. serializationObject.geometries.toruses = [];
  80706. serializationObject.geometries.grounds = [];
  80707. serializationObject.geometries.planes = [];
  80708. serializationObject.geometries.torusKnots = [];
  80709. serializationObject.geometries.vertexData = [];
  80710. }
  80711. serializeGeometry(geometry, serializationObject.geometries);
  80712. }
  80713. // Skeletons
  80714. if (mesh.skeleton) {
  80715. serializationObject.skeletons = serializationObject.skeletons || [];
  80716. serializationObject.skeletons.push(mesh.skeleton.serialize());
  80717. }
  80718. //serialize the actual mesh
  80719. serializationObject.meshes = serializationObject.meshes || [];
  80720. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  80721. }
  80722. };
  80723. var SceneSerializer = /** @class */ (function () {
  80724. function SceneSerializer() {
  80725. }
  80726. SceneSerializer.ClearCache = function () {
  80727. serializedGeometries = [];
  80728. };
  80729. SceneSerializer.Serialize = function (scene) {
  80730. var serializationObject = {};
  80731. SceneSerializer.ClearCache();
  80732. // Scene
  80733. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  80734. serializationObject.autoClear = scene.autoClear;
  80735. serializationObject.clearColor = scene.clearColor.asArray();
  80736. serializationObject.ambientColor = scene.ambientColor.asArray();
  80737. serializationObject.gravity = scene.gravity.asArray();
  80738. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  80739. serializationObject.workerCollisions = scene.workerCollisions;
  80740. // Fog
  80741. if (scene.fogMode && scene.fogMode !== 0) {
  80742. serializationObject.fogMode = scene.fogMode;
  80743. serializationObject.fogColor = scene.fogColor.asArray();
  80744. serializationObject.fogStart = scene.fogStart;
  80745. serializationObject.fogEnd = scene.fogEnd;
  80746. serializationObject.fogDensity = scene.fogDensity;
  80747. }
  80748. //Physics
  80749. if (scene.isPhysicsEnabled()) {
  80750. var physicEngine = scene.getPhysicsEngine();
  80751. if (physicEngine) {
  80752. serializationObject.physicsEnabled = true;
  80753. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  80754. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  80755. }
  80756. }
  80757. // Metadata
  80758. if (scene.metadata) {
  80759. serializationObject.metadata = scene.metadata;
  80760. }
  80761. // Morph targets
  80762. serializationObject.morphTargetManagers = [];
  80763. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  80764. var abstractMesh = _a[_i];
  80765. var manager = abstractMesh.morphTargetManager;
  80766. if (manager) {
  80767. serializationObject.morphTargetManagers.push(manager.serialize());
  80768. }
  80769. }
  80770. // Lights
  80771. serializationObject.lights = [];
  80772. var index;
  80773. var light;
  80774. for (index = 0; index < scene.lights.length; index++) {
  80775. light = scene.lights[index];
  80776. if (!light.doNotSerialize) {
  80777. serializationObject.lights.push(light.serialize());
  80778. }
  80779. }
  80780. // Cameras
  80781. serializationObject.cameras = [];
  80782. for (index = 0; index < scene.cameras.length; index++) {
  80783. var camera = scene.cameras[index];
  80784. if (!camera.doNotSerialize) {
  80785. serializationObject.cameras.push(camera.serialize());
  80786. }
  80787. }
  80788. if (scene.activeCamera) {
  80789. serializationObject.activeCameraID = scene.activeCamera.id;
  80790. }
  80791. // Animations
  80792. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  80793. // Materials
  80794. serializationObject.materials = [];
  80795. serializationObject.multiMaterials = [];
  80796. var material;
  80797. for (index = 0; index < scene.materials.length; index++) {
  80798. material = scene.materials[index];
  80799. if (!material.doNotSerialize) {
  80800. serializationObject.materials.push(material.serialize());
  80801. }
  80802. }
  80803. // MultiMaterials
  80804. serializationObject.multiMaterials = [];
  80805. for (index = 0; index < scene.multiMaterials.length; index++) {
  80806. var multiMaterial = scene.multiMaterials[index];
  80807. serializationObject.multiMaterials.push(multiMaterial.serialize());
  80808. }
  80809. // Environment texture
  80810. if (scene.environmentTexture) {
  80811. serializationObject.environmentTexture = scene.environmentTexture.name;
  80812. }
  80813. // Skeletons
  80814. serializationObject.skeletons = [];
  80815. for (index = 0; index < scene.skeletons.length; index++) {
  80816. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  80817. }
  80818. // Transform nodes
  80819. serializationObject.transformNodes = [];
  80820. for (index = 0; index < scene.transformNodes.length; index++) {
  80821. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  80822. }
  80823. // Geometries
  80824. serializationObject.geometries = {};
  80825. serializationObject.geometries.boxes = [];
  80826. serializationObject.geometries.spheres = [];
  80827. serializationObject.geometries.cylinders = [];
  80828. serializationObject.geometries.toruses = [];
  80829. serializationObject.geometries.grounds = [];
  80830. serializationObject.geometries.planes = [];
  80831. serializationObject.geometries.torusKnots = [];
  80832. serializationObject.geometries.vertexData = [];
  80833. serializedGeometries = [];
  80834. var geometries = scene.getGeometries();
  80835. for (index = 0; index < geometries.length; index++) {
  80836. var geometry = geometries[index];
  80837. if (geometry.isReady()) {
  80838. serializeGeometry(geometry, serializationObject.geometries);
  80839. }
  80840. }
  80841. // Meshes
  80842. serializationObject.meshes = [];
  80843. for (index = 0; index < scene.meshes.length; index++) {
  80844. var abstractMesh = scene.meshes[index];
  80845. if (abstractMesh instanceof BABYLON.Mesh) {
  80846. var mesh = abstractMesh;
  80847. if (!mesh.doNotSerialize) {
  80848. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  80849. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  80850. }
  80851. }
  80852. }
  80853. }
  80854. // Particles Systems
  80855. serializationObject.particleSystems = [];
  80856. for (index = 0; index < scene.particleSystems.length; index++) {
  80857. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  80858. }
  80859. // Lens flares
  80860. serializationObject.lensFlareSystems = [];
  80861. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  80862. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  80863. }
  80864. // Shadows
  80865. serializationObject.shadowGenerators = [];
  80866. for (index = 0; index < scene.lights.length; index++) {
  80867. light = scene.lights[index];
  80868. var shadowGenerator = light.getShadowGenerator();
  80869. if (shadowGenerator) {
  80870. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  80871. }
  80872. }
  80873. // Action Manager
  80874. if (scene.actionManager) {
  80875. serializationObject.actions = scene.actionManager.serialize("scene");
  80876. }
  80877. // Audio
  80878. serializationObject.sounds = [];
  80879. for (index = 0; index < scene.soundTracks.length; index++) {
  80880. var soundtrack = scene.soundTracks[index];
  80881. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  80882. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  80883. }
  80884. }
  80885. return serializationObject;
  80886. };
  80887. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  80888. if (withParents === void 0) { withParents = false; }
  80889. if (withChildren === void 0) { withChildren = false; }
  80890. var serializationObject = {};
  80891. SceneSerializer.ClearCache();
  80892. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  80893. if (withParents || withChildren) {
  80894. //deliberate for loop! not for each, appended should be processed as well.
  80895. for (var i = 0; i < toSerialize.length; ++i) {
  80896. if (withChildren) {
  80897. toSerialize[i].getDescendants().forEach(function (node) {
  80898. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  80899. toSerialize.push(node);
  80900. }
  80901. });
  80902. }
  80903. //make sure the array doesn't contain the object already
  80904. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  80905. toSerialize.push(toSerialize[i].parent);
  80906. }
  80907. }
  80908. }
  80909. toSerialize.forEach(function (mesh) {
  80910. finalizeSingleMesh(mesh, serializationObject);
  80911. });
  80912. return serializationObject;
  80913. };
  80914. return SceneSerializer;
  80915. }());
  80916. BABYLON.SceneSerializer = SceneSerializer;
  80917. })(BABYLON || (BABYLON = {}));
  80918. //# sourceMappingURL=babylon.sceneSerializer.js.map
  80919. var BABYLON;
  80920. (function (BABYLON) {
  80921. var ReflectionProbe = /** @class */ (function () {
  80922. function ReflectionProbe(name, size, scene, generateMipMaps) {
  80923. if (generateMipMaps === void 0) { generateMipMaps = true; }
  80924. var _this = this;
  80925. this.name = name;
  80926. this._viewMatrix = BABYLON.Matrix.Identity();
  80927. this._target = BABYLON.Vector3.Zero();
  80928. this._add = BABYLON.Vector3.Zero();
  80929. this.invertYAxis = false;
  80930. this.position = BABYLON.Vector3.Zero();
  80931. this._scene = scene;
  80932. this._scene.reflectionProbes.push(this);
  80933. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  80934. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  80935. switch (faceIndex) {
  80936. case 0:
  80937. _this._add.copyFromFloats(1, 0, 0);
  80938. break;
  80939. case 1:
  80940. _this._add.copyFromFloats(-1, 0, 0);
  80941. break;
  80942. case 2:
  80943. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  80944. break;
  80945. case 3:
  80946. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  80947. break;
  80948. case 4:
  80949. _this._add.copyFromFloats(0, 0, 1);
  80950. break;
  80951. case 5:
  80952. _this._add.copyFromFloats(0, 0, -1);
  80953. break;
  80954. }
  80955. if (_this._attachedMesh) {
  80956. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  80957. }
  80958. _this.position.addToRef(_this._add, _this._target);
  80959. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  80960. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  80961. scene._forcedViewPosition = _this.position;
  80962. });
  80963. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  80964. scene._forcedViewPosition = null;
  80965. scene.updateTransformMatrix(true);
  80966. });
  80967. if (scene.activeCamera) {
  80968. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  80969. }
  80970. }
  80971. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  80972. get: function () {
  80973. return this._renderTargetTexture.samples;
  80974. },
  80975. set: function (value) {
  80976. this._renderTargetTexture.samples = value;
  80977. },
  80978. enumerable: true,
  80979. configurable: true
  80980. });
  80981. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  80982. get: function () {
  80983. return this._renderTargetTexture.refreshRate;
  80984. },
  80985. set: function (value) {
  80986. this._renderTargetTexture.refreshRate = value;
  80987. },
  80988. enumerable: true,
  80989. configurable: true
  80990. });
  80991. ReflectionProbe.prototype.getScene = function () {
  80992. return this._scene;
  80993. };
  80994. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  80995. get: function () {
  80996. return this._renderTargetTexture;
  80997. },
  80998. enumerable: true,
  80999. configurable: true
  81000. });
  81001. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  81002. get: function () {
  81003. return this._renderTargetTexture.renderList;
  81004. },
  81005. enumerable: true,
  81006. configurable: true
  81007. });
  81008. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  81009. this._attachedMesh = mesh;
  81010. };
  81011. /**
  81012. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  81013. *
  81014. * @param renderingGroupId The rendering group id corresponding to its index
  81015. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  81016. */
  81017. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  81018. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  81019. };
  81020. ReflectionProbe.prototype.dispose = function () {
  81021. var index = this._scene.reflectionProbes.indexOf(this);
  81022. if (index !== -1) {
  81023. // Remove from the scene if found
  81024. this._scene.reflectionProbes.splice(index, 1);
  81025. }
  81026. if (this._renderTargetTexture) {
  81027. this._renderTargetTexture.dispose();
  81028. this._renderTargetTexture = null;
  81029. }
  81030. };
  81031. return ReflectionProbe;
  81032. }());
  81033. BABYLON.ReflectionProbe = ReflectionProbe;
  81034. })(BABYLON || (BABYLON = {}));
  81035. //# sourceMappingURL=babylon.reflectionProbe.js.map
  81036. var BABYLON;
  81037. (function (BABYLON) {
  81038. var Layer = /** @class */ (function () {
  81039. function Layer(name, imgUrl, scene, isBackground, color) {
  81040. this.name = name;
  81041. this.scale = new BABYLON.Vector2(1, 1);
  81042. this.offset = new BABYLON.Vector2(0, 0);
  81043. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  81044. this.layerMask = 0x0FFFFFFF;
  81045. this._vertexBuffers = {};
  81046. // Events
  81047. /**
  81048. * An event triggered when the layer is disposed.
  81049. * @type {BABYLON.Observable}
  81050. */
  81051. this.onDisposeObservable = new BABYLON.Observable();
  81052. /**
  81053. * An event triggered before rendering the scene
  81054. * @type {BABYLON.Observable}
  81055. */
  81056. this.onBeforeRenderObservable = new BABYLON.Observable();
  81057. /**
  81058. * An event triggered after rendering the scene
  81059. * @type {BABYLON.Observable}
  81060. */
  81061. this.onAfterRenderObservable = new BABYLON.Observable();
  81062. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  81063. this.isBackground = isBackground === undefined ? true : isBackground;
  81064. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  81065. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  81066. this._scene.layers.push(this);
  81067. var engine = this._scene.getEngine();
  81068. // VBO
  81069. var vertices = [];
  81070. vertices.push(1, 1);
  81071. vertices.push(-1, 1);
  81072. vertices.push(-1, -1);
  81073. vertices.push(1, -1);
  81074. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  81075. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  81076. this._createIndexBuffer();
  81077. // Effects
  81078. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  81079. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  81080. }
  81081. Object.defineProperty(Layer.prototype, "onDispose", {
  81082. set: function (callback) {
  81083. if (this._onDisposeObserver) {
  81084. this.onDisposeObservable.remove(this._onDisposeObserver);
  81085. }
  81086. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  81087. },
  81088. enumerable: true,
  81089. configurable: true
  81090. });
  81091. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  81092. set: function (callback) {
  81093. if (this._onBeforeRenderObserver) {
  81094. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  81095. }
  81096. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  81097. },
  81098. enumerable: true,
  81099. configurable: true
  81100. });
  81101. Object.defineProperty(Layer.prototype, "onAfterRender", {
  81102. set: function (callback) {
  81103. if (this._onAfterRenderObserver) {
  81104. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  81105. }
  81106. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  81107. },
  81108. enumerable: true,
  81109. configurable: true
  81110. });
  81111. Layer.prototype._createIndexBuffer = function () {
  81112. var engine = this._scene.getEngine();
  81113. // Indices
  81114. var indices = [];
  81115. indices.push(0);
  81116. indices.push(1);
  81117. indices.push(2);
  81118. indices.push(0);
  81119. indices.push(2);
  81120. indices.push(3);
  81121. this._indexBuffer = engine.createIndexBuffer(indices);
  81122. };
  81123. Layer.prototype._rebuild = function () {
  81124. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  81125. if (vb) {
  81126. vb._rebuild();
  81127. }
  81128. this._createIndexBuffer();
  81129. };
  81130. Layer.prototype.render = function () {
  81131. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  81132. // Check
  81133. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  81134. return;
  81135. var engine = this._scene.getEngine();
  81136. this.onBeforeRenderObservable.notifyObservers(this);
  81137. // Render
  81138. engine.enableEffect(currentEffect);
  81139. engine.setState(false);
  81140. // Texture
  81141. currentEffect.setTexture("textureSampler", this.texture);
  81142. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  81143. // Color
  81144. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  81145. // Scale / offset
  81146. currentEffect.setVector2("offset", this.offset);
  81147. currentEffect.setVector2("scale", this.scale);
  81148. // VBOs
  81149. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  81150. // Draw order
  81151. if (!this.alphaTest) {
  81152. engine.setAlphaMode(this.alphaBlendingMode);
  81153. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  81154. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  81155. }
  81156. else {
  81157. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  81158. }
  81159. this.onAfterRenderObservable.notifyObservers(this);
  81160. };
  81161. Layer.prototype.dispose = function () {
  81162. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  81163. if (vertexBuffer) {
  81164. vertexBuffer.dispose();
  81165. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  81166. }
  81167. if (this._indexBuffer) {
  81168. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  81169. this._indexBuffer = null;
  81170. }
  81171. if (this.texture) {
  81172. this.texture.dispose();
  81173. this.texture = null;
  81174. }
  81175. // Remove from scene
  81176. var index = this._scene.layers.indexOf(this);
  81177. this._scene.layers.splice(index, 1);
  81178. // Callback
  81179. this.onDisposeObservable.notifyObservers(this);
  81180. this.onDisposeObservable.clear();
  81181. this.onAfterRenderObservable.clear();
  81182. this.onBeforeRenderObservable.clear();
  81183. };
  81184. return Layer;
  81185. }());
  81186. BABYLON.Layer = Layer;
  81187. })(BABYLON || (BABYLON = {}));
  81188. //# sourceMappingURL=babylon.layer.js.map
  81189. var BABYLON;
  81190. (function (BABYLON) {
  81191. var TextureTools = /** @class */ (function () {
  81192. function TextureTools() {
  81193. }
  81194. /**
  81195. * Uses the GPU to create a copy texture rescaled at a given size
  81196. * @param texture Texture to copy from
  81197. * @param width Desired width
  81198. * @param height Desired height
  81199. * @return Generated texture
  81200. */
  81201. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  81202. if (useBilinearMode === void 0) { useBilinearMode = true; }
  81203. var scene = texture.getScene();
  81204. var engine = scene.getEngine();
  81205. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  81206. rtt.wrapU = texture.wrapU;
  81207. rtt.wrapV = texture.wrapV;
  81208. rtt.uOffset = texture.uOffset;
  81209. rtt.vOffset = texture.vOffset;
  81210. rtt.uScale = texture.uScale;
  81211. rtt.vScale = texture.vScale;
  81212. rtt.uAng = texture.uAng;
  81213. rtt.vAng = texture.vAng;
  81214. rtt.wAng = texture.wAng;
  81215. rtt.coordinatesIndex = texture.coordinatesIndex;
  81216. rtt.level = texture.level;
  81217. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  81218. rtt._texture.isReady = false;
  81219. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81220. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81221. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  81222. passPostProcess.getEffect().executeWhenCompiled(function () {
  81223. passPostProcess.onApply = function (effect) {
  81224. effect.setTexture("textureSampler", texture);
  81225. };
  81226. var internalTexture = rtt.getInternalTexture();
  81227. if (internalTexture) {
  81228. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  81229. engine.unBindFramebuffer(internalTexture);
  81230. rtt.disposeFramebufferObjects();
  81231. passPostProcess.dispose();
  81232. internalTexture.isReady = true;
  81233. }
  81234. });
  81235. return rtt;
  81236. };
  81237. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  81238. if (!scene._environmentBRDFTexture) {
  81239. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  81240. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81241. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81242. scene._environmentBRDFTexture = texture;
  81243. }
  81244. return scene._environmentBRDFTexture;
  81245. };
  81246. 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=";
  81247. return TextureTools;
  81248. }());
  81249. BABYLON.TextureTools = TextureTools;
  81250. })(BABYLON || (BABYLON = {}));
  81251. //# sourceMappingURL=babylon.textureTools.js.map
  81252. var BABYLON;
  81253. (function (BABYLON) {
  81254. var FramingBehavior = /** @class */ (function () {
  81255. function FramingBehavior() {
  81256. this._mode = FramingBehavior.FitFrustumSidesMode;
  81257. this._radiusScale = 1.0;
  81258. this._positionScale = 0.5;
  81259. this._defaultElevation = 0.3;
  81260. this._elevationReturnTime = 1500;
  81261. this._elevationReturnWaitTime = 1000;
  81262. this._zoomStopsAnimation = false;
  81263. this._framingTime = 1500;
  81264. this._isPointerDown = false;
  81265. this._lastInteractionTime = -Infinity;
  81266. // Framing control
  81267. this._animatables = new Array();
  81268. this._betaIsAnimating = false;
  81269. }
  81270. Object.defineProperty(FramingBehavior.prototype, "name", {
  81271. get: function () {
  81272. return "Framing";
  81273. },
  81274. enumerable: true,
  81275. configurable: true
  81276. });
  81277. Object.defineProperty(FramingBehavior.prototype, "mode", {
  81278. /**
  81279. * Gets current mode used by the behavior.
  81280. */
  81281. get: function () {
  81282. return this._mode;
  81283. },
  81284. /**
  81285. * Sets the current mode used by the behavior
  81286. */
  81287. set: function (mode) {
  81288. this._mode = mode;
  81289. },
  81290. enumerable: true,
  81291. configurable: true
  81292. });
  81293. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  81294. /**
  81295. * Gets the scale applied to the radius
  81296. */
  81297. get: function () {
  81298. return this._radiusScale;
  81299. },
  81300. /**
  81301. * Sets the scale applied to the radius (1 by default)
  81302. */
  81303. set: function (radius) {
  81304. this._radiusScale = radius;
  81305. },
  81306. enumerable: true,
  81307. configurable: true
  81308. });
  81309. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  81310. /**
  81311. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  81312. */
  81313. get: function () {
  81314. return this._positionScale;
  81315. },
  81316. /**
  81317. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  81318. */
  81319. set: function (scale) {
  81320. this._positionScale = scale;
  81321. },
  81322. enumerable: true,
  81323. configurable: true
  81324. });
  81325. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  81326. /**
  81327. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  81328. * behaviour is triggered, in radians.
  81329. */
  81330. get: function () {
  81331. return this._defaultElevation;
  81332. },
  81333. /**
  81334. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  81335. * behaviour is triggered, in radians.
  81336. */
  81337. set: function (elevation) {
  81338. this._defaultElevation = elevation;
  81339. },
  81340. enumerable: true,
  81341. configurable: true
  81342. });
  81343. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  81344. /**
  81345. * Gets the time (in milliseconds) taken to return to the default beta position.
  81346. * Negative value indicates camera should not return to default.
  81347. */
  81348. get: function () {
  81349. return this._elevationReturnTime;
  81350. },
  81351. /**
  81352. * Sets the time (in milliseconds) taken to return to the default beta position.
  81353. * Negative value indicates camera should not return to default.
  81354. */
  81355. set: function (speed) {
  81356. this._elevationReturnTime = speed;
  81357. },
  81358. enumerable: true,
  81359. configurable: true
  81360. });
  81361. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  81362. /**
  81363. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  81364. */
  81365. get: function () {
  81366. return this._elevationReturnWaitTime;
  81367. },
  81368. /**
  81369. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  81370. */
  81371. set: function (time) {
  81372. this._elevationReturnWaitTime = time;
  81373. },
  81374. enumerable: true,
  81375. configurable: true
  81376. });
  81377. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  81378. /**
  81379. * Gets the flag that indicates if user zooming should stop animation.
  81380. */
  81381. get: function () {
  81382. return this._zoomStopsAnimation;
  81383. },
  81384. /**
  81385. * Sets the flag that indicates if user zooming should stop animation.
  81386. */
  81387. set: function (flag) {
  81388. this._zoomStopsAnimation = flag;
  81389. },
  81390. enumerable: true,
  81391. configurable: true
  81392. });
  81393. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  81394. /**
  81395. * Gets the transition time when framing the mesh, in milliseconds
  81396. */
  81397. get: function () {
  81398. return this._framingTime;
  81399. },
  81400. /**
  81401. * Sets the transition time when framing the mesh, in milliseconds
  81402. */
  81403. set: function (time) {
  81404. this._framingTime = time;
  81405. },
  81406. enumerable: true,
  81407. configurable: true
  81408. });
  81409. FramingBehavior.prototype.init = function () {
  81410. // Do notihng
  81411. };
  81412. FramingBehavior.prototype.attach = function (camera) {
  81413. var _this = this;
  81414. this._attachedCamera = camera;
  81415. var scene = this._attachedCamera.getScene();
  81416. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  81417. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  81418. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  81419. _this._isPointerDown = true;
  81420. return;
  81421. }
  81422. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  81423. _this._isPointerDown = false;
  81424. }
  81425. });
  81426. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  81427. if (mesh) {
  81428. _this.zoomOnMesh(mesh);
  81429. }
  81430. });
  81431. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  81432. // Stop the animation if there is user interaction and the animation should stop for this interaction
  81433. _this._applyUserInteraction();
  81434. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  81435. // back to the default position after a given timeout
  81436. _this._maintainCameraAboveGround();
  81437. });
  81438. };
  81439. FramingBehavior.prototype.detach = function () {
  81440. if (!this._attachedCamera) {
  81441. return;
  81442. }
  81443. var scene = this._attachedCamera.getScene();
  81444. if (this._onPrePointerObservableObserver) {
  81445. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  81446. }
  81447. if (this._onAfterCheckInputsObserver) {
  81448. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  81449. }
  81450. if (this._onMeshTargetChangedObserver) {
  81451. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  81452. }
  81453. this._attachedCamera = null;
  81454. };
  81455. /**
  81456. * Targets the given mesh and updates zoom level accordingly.
  81457. * @param mesh The mesh to target.
  81458. * @param radius Optional. If a cached radius position already exists, overrides default.
  81459. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  81460. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  81461. * @param onAnimationEnd Callback triggered at the end of the framing animation
  81462. */
  81463. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  81464. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  81465. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  81466. mesh.computeWorldMatrix(true);
  81467. var boundingBox = mesh.getBoundingInfo().boundingBox;
  81468. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  81469. };
  81470. /**
  81471. * Targets the given mesh with its children and updates zoom level accordingly.
  81472. * @param mesh The mesh to target.
  81473. * @param radius Optional. If a cached radius position already exists, overrides default.
  81474. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  81475. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  81476. * @param onAnimationEnd Callback triggered at the end of the framing animation
  81477. */
  81478. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  81479. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  81480. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  81481. mesh.computeWorldMatrix(true);
  81482. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  81483. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  81484. };
  81485. /**
  81486. * Targets the given meshes with their children and updates zoom level accordingly.
  81487. * @param meshes The mesh to target.
  81488. * @param radius Optional. If a cached radius position already exists, overrides default.
  81489. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  81490. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  81491. * @param onAnimationEnd Callback triggered at the end of the framing animation
  81492. */
  81493. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  81494. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  81495. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  81496. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  81497. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  81498. for (var i = 0; i < meshes.length; i++) {
  81499. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  81500. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  81501. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  81502. }
  81503. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  81504. };
  81505. /**
  81506. * Targets the given mesh and updates zoom level accordingly.
  81507. * @param mesh The mesh to target.
  81508. * @param radius Optional. If a cached radius position already exists, overrides default.
  81509. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  81510. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  81511. * @param onAnimationEnd Callback triggered at the end of the framing animation
  81512. */
  81513. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  81514. var _this = this;
  81515. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  81516. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  81517. var zoomTarget;
  81518. if (!this._attachedCamera) {
  81519. return;
  81520. }
  81521. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  81522. var bottom = minimumWorld.y;
  81523. var top = maximumWorld.y;
  81524. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  81525. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  81526. if (focusOnOriginXZ) {
  81527. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  81528. }
  81529. else {
  81530. var centerWorld = minimumWorld.add(radiusWorld);
  81531. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  81532. }
  81533. if (!this._vectorTransition) {
  81534. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  81535. }
  81536. this._betaIsAnimating = true;
  81537. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  81538. if (animatable) {
  81539. this._animatables.push(animatable);
  81540. }
  81541. // sets the radius and lower radius bounds
  81542. // Small delta ensures camera is not always at lower zoom limit.
  81543. var radius = 0;
  81544. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  81545. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  81546. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  81547. radius = position;
  81548. }
  81549. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  81550. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  81551. if (this._attachedCamera.lowerRadiusLimit === null) {
  81552. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  81553. }
  81554. }
  81555. // Set sensibilities
  81556. var extend = maximumWorld.subtract(minimumWorld).length();
  81557. this._attachedCamera.panningSensibility = 5000 / extend;
  81558. this._attachedCamera.wheelPrecision = 100 / radius;
  81559. // transition to new radius
  81560. if (!this._radiusTransition) {
  81561. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  81562. }
  81563. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  81564. if (onAnimationEnd) {
  81565. onAnimationEnd();
  81566. }
  81567. if (_this._attachedCamera) {
  81568. _this._attachedCamera.storeState();
  81569. }
  81570. });
  81571. if (animatable) {
  81572. this._animatables.push(animatable);
  81573. }
  81574. };
  81575. /**
  81576. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  81577. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  81578. * frustum width.
  81579. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  81580. * to fully enclose the mesh in the viewing frustum.
  81581. */
  81582. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  81583. var size = maximumWorld.subtract(minimumWorld);
  81584. var boxVectorGlobalDiagonal = size.length();
  81585. var frustumSlope = this._getFrustumSlope();
  81586. // Formula for setting distance
  81587. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  81588. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  81589. // Horizon distance
  81590. var radius = radiusWithoutFraming * this._radiusScale;
  81591. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  81592. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  81593. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  81594. var camera = this._attachedCamera;
  81595. if (!camera) {
  81596. return 0;
  81597. }
  81598. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  81599. // Don't exceed the requested limit
  81600. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  81601. }
  81602. // Don't exceed the upper radius limit
  81603. if (camera.upperRadiusLimit) {
  81604. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  81605. }
  81606. return distance;
  81607. };
  81608. /**
  81609. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  81610. * is automatically returned to its default position (expected to be above ground plane).
  81611. */
  81612. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  81613. var _this = this;
  81614. if (this._elevationReturnTime < 0) {
  81615. return;
  81616. }
  81617. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  81618. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  81619. var limitBeta = Math.PI * 0.5;
  81620. // Bring the camera back up if below the ground plane
  81621. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  81622. this._betaIsAnimating = true;
  81623. //Transition to new position
  81624. this.stopAllAnimations();
  81625. if (!this._betaTransition) {
  81626. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  81627. }
  81628. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  81629. _this._clearAnimationLocks();
  81630. _this.stopAllAnimations();
  81631. });
  81632. if (animatabe) {
  81633. this._animatables.push(animatabe);
  81634. }
  81635. }
  81636. };
  81637. /**
  81638. * Returns the frustum slope based on the canvas ratio and camera FOV
  81639. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  81640. */
  81641. FramingBehavior.prototype._getFrustumSlope = function () {
  81642. // Calculate the viewport ratio
  81643. // Aspect Ratio is Height/Width.
  81644. var camera = this._attachedCamera;
  81645. if (!camera) {
  81646. return BABYLON.Vector2.Zero();
  81647. }
  81648. var engine = camera.getScene().getEngine();
  81649. var aspectRatio = engine.getAspectRatio(camera);
  81650. // Camera FOV is the vertical field of view (top-bottom) in radians.
  81651. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  81652. var frustumSlopeY = Math.tan(camera.fov / 2);
  81653. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  81654. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  81655. // along the forward vector.
  81656. var frustumSlopeX = frustumSlopeY * aspectRatio;
  81657. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  81658. };
  81659. /**
  81660. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  81661. */
  81662. FramingBehavior.prototype._clearAnimationLocks = function () {
  81663. this._betaIsAnimating = false;
  81664. };
  81665. /**
  81666. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  81667. */
  81668. FramingBehavior.prototype._applyUserInteraction = function () {
  81669. if (this.isUserIsMoving) {
  81670. this._lastInteractionTime = BABYLON.Tools.Now;
  81671. this.stopAllAnimations();
  81672. this._clearAnimationLocks();
  81673. }
  81674. };
  81675. /**
  81676. * Stops and removes all animations that have been applied to the camera
  81677. */
  81678. FramingBehavior.prototype.stopAllAnimations = function () {
  81679. if (this._attachedCamera) {
  81680. this._attachedCamera.animations = [];
  81681. }
  81682. while (this._animatables.length) {
  81683. if (this._animatables[0]) {
  81684. this._animatables[0].onAnimationEnd = null;
  81685. this._animatables[0].stop();
  81686. }
  81687. this._animatables.shift();
  81688. }
  81689. };
  81690. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  81691. /**
  81692. * Gets a value indicating if the user is moving the camera
  81693. */
  81694. get: function () {
  81695. if (!this._attachedCamera) {
  81696. return false;
  81697. }
  81698. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  81699. this._attachedCamera.inertialBetaOffset !== 0 ||
  81700. this._attachedCamera.inertialRadiusOffset !== 0 ||
  81701. this._attachedCamera.inertialPanningX !== 0 ||
  81702. this._attachedCamera.inertialPanningY !== 0 ||
  81703. this._isPointerDown;
  81704. },
  81705. enumerable: true,
  81706. configurable: true
  81707. });
  81708. /**
  81709. * The easing function used by animations
  81710. */
  81711. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  81712. /**
  81713. * The easing mode used by animations
  81714. */
  81715. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  81716. // Statics
  81717. /**
  81718. * The camera can move all the way towards the mesh.
  81719. */
  81720. FramingBehavior.IgnoreBoundsSizeMode = 0;
  81721. /**
  81722. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  81723. */
  81724. FramingBehavior.FitFrustumSidesMode = 1;
  81725. return FramingBehavior;
  81726. }());
  81727. BABYLON.FramingBehavior = FramingBehavior;
  81728. })(BABYLON || (BABYLON = {}));
  81729. //# sourceMappingURL=babylon.framingBehavior.js.map
  81730. var BABYLON;
  81731. (function (BABYLON) {
  81732. /**
  81733. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  81734. */
  81735. var BouncingBehavior = /** @class */ (function () {
  81736. function BouncingBehavior() {
  81737. /**
  81738. * The duration of the animation, in milliseconds
  81739. */
  81740. this.transitionDuration = 450;
  81741. /**
  81742. * Length of the distance animated by the transition when lower radius is reached
  81743. */
  81744. this.lowerRadiusTransitionRange = 2;
  81745. /**
  81746. * Length of the distance animated by the transition when upper radius is reached
  81747. */
  81748. this.upperRadiusTransitionRange = -2;
  81749. this._autoTransitionRange = false;
  81750. // Animations
  81751. this._radiusIsAnimating = false;
  81752. this._radiusBounceTransition = null;
  81753. this._animatables = new Array();
  81754. }
  81755. Object.defineProperty(BouncingBehavior.prototype, "name", {
  81756. get: function () {
  81757. return "Bouncing";
  81758. },
  81759. enumerable: true,
  81760. configurable: true
  81761. });
  81762. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  81763. /**
  81764. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  81765. */
  81766. get: function () {
  81767. return this._autoTransitionRange;
  81768. },
  81769. /**
  81770. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  81771. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  81772. */
  81773. set: function (value) {
  81774. var _this = this;
  81775. if (this._autoTransitionRange === value) {
  81776. return;
  81777. }
  81778. this._autoTransitionRange = value;
  81779. var camera = this._attachedCamera;
  81780. if (!camera) {
  81781. return;
  81782. }
  81783. if (value) {
  81784. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  81785. if (!mesh) {
  81786. return;
  81787. }
  81788. mesh.computeWorldMatrix(true);
  81789. var diagonal = mesh.getBoundingInfo().diagonalLength;
  81790. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  81791. _this.upperRadiusTransitionRange = diagonal * 0.05;
  81792. });
  81793. }
  81794. else if (this._onMeshTargetChangedObserver) {
  81795. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  81796. }
  81797. },
  81798. enumerable: true,
  81799. configurable: true
  81800. });
  81801. BouncingBehavior.prototype.init = function () {
  81802. // Do notihng
  81803. };
  81804. BouncingBehavior.prototype.attach = function (camera) {
  81805. var _this = this;
  81806. this._attachedCamera = camera;
  81807. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  81808. if (!_this._attachedCamera) {
  81809. return;
  81810. }
  81811. // Add the bounce animation to the lower radius limit
  81812. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  81813. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  81814. }
  81815. // Add the bounce animation to the upper radius limit
  81816. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  81817. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  81818. }
  81819. });
  81820. };
  81821. BouncingBehavior.prototype.detach = function () {
  81822. if (!this._attachedCamera) {
  81823. return;
  81824. }
  81825. if (this._onAfterCheckInputsObserver) {
  81826. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  81827. }
  81828. if (this._onMeshTargetChangedObserver) {
  81829. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  81830. }
  81831. this._attachedCamera = null;
  81832. };
  81833. /**
  81834. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  81835. * @param radiusLimit The limit to check against.
  81836. * @return Bool to indicate if at limit.
  81837. */
  81838. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  81839. if (!this._attachedCamera) {
  81840. return false;
  81841. }
  81842. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  81843. return true;
  81844. }
  81845. return false;
  81846. };
  81847. /**
  81848. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  81849. * @param radiusDelta The delta by which to animate to. Can be negative.
  81850. */
  81851. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  81852. var _this = this;
  81853. if (!this._attachedCamera) {
  81854. return;
  81855. }
  81856. if (!this._radiusBounceTransition) {
  81857. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  81858. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  81859. }
  81860. // Prevent zoom until bounce has completed
  81861. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  81862. this._attachedCamera.wheelPrecision = Infinity;
  81863. this._attachedCamera.inertialRadiusOffset = 0;
  81864. // Animate to the radius limit
  81865. this.stopAllAnimations();
  81866. this._radiusIsAnimating = true;
  81867. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  81868. if (animatable) {
  81869. this._animatables.push(animatable);
  81870. }
  81871. };
  81872. /**
  81873. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  81874. */
  81875. BouncingBehavior.prototype._clearAnimationLocks = function () {
  81876. this._radiusIsAnimating = false;
  81877. if (this._attachedCamera) {
  81878. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  81879. }
  81880. };
  81881. /**
  81882. * Stops and removes all animations that have been applied to the camera
  81883. */
  81884. BouncingBehavior.prototype.stopAllAnimations = function () {
  81885. if (this._attachedCamera) {
  81886. this._attachedCamera.animations = [];
  81887. }
  81888. while (this._animatables.length) {
  81889. this._animatables[0].onAnimationEnd = null;
  81890. this._animatables[0].stop();
  81891. this._animatables.shift();
  81892. }
  81893. };
  81894. /**
  81895. * The easing function used by animations
  81896. */
  81897. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  81898. /**
  81899. * The easing mode used by animations
  81900. */
  81901. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  81902. return BouncingBehavior;
  81903. }());
  81904. BABYLON.BouncingBehavior = BouncingBehavior;
  81905. })(BABYLON || (BABYLON = {}));
  81906. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  81907. var BABYLON;
  81908. (function (BABYLON) {
  81909. var AutoRotationBehavior = /** @class */ (function () {
  81910. function AutoRotationBehavior() {
  81911. this._zoomStopsAnimation = false;
  81912. this._idleRotationSpeed = 0.05;
  81913. this._idleRotationWaitTime = 2000;
  81914. this._idleRotationSpinupTime = 2000;
  81915. this._isPointerDown = false;
  81916. this._lastFrameTime = null;
  81917. this._lastInteractionTime = -Infinity;
  81918. this._cameraRotationSpeed = 0;
  81919. this._lastFrameRadius = 0;
  81920. }
  81921. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  81922. get: function () {
  81923. return "AutoRotation";
  81924. },
  81925. enumerable: true,
  81926. configurable: true
  81927. });
  81928. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  81929. /**
  81930. * Gets the flag that indicates if user zooming should stop animation.
  81931. */
  81932. get: function () {
  81933. return this._zoomStopsAnimation;
  81934. },
  81935. /**
  81936. * Sets the flag that indicates if user zooming should stop animation.
  81937. */
  81938. set: function (flag) {
  81939. this._zoomStopsAnimation = flag;
  81940. },
  81941. enumerable: true,
  81942. configurable: true
  81943. });
  81944. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  81945. /**
  81946. * Gets the default speed at which the camera rotates around the model.
  81947. */
  81948. get: function () {
  81949. return this._idleRotationSpeed;
  81950. },
  81951. /**
  81952. * Sets the default speed at which the camera rotates around the model.
  81953. */
  81954. set: function (speed) {
  81955. this._idleRotationSpeed = speed;
  81956. },
  81957. enumerable: true,
  81958. configurable: true
  81959. });
  81960. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  81961. /**
  81962. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  81963. */
  81964. get: function () {
  81965. return this._idleRotationWaitTime;
  81966. },
  81967. /**
  81968. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  81969. */
  81970. set: function (time) {
  81971. this._idleRotationWaitTime = time;
  81972. },
  81973. enumerable: true,
  81974. configurable: true
  81975. });
  81976. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  81977. /**
  81978. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  81979. */
  81980. get: function () {
  81981. return this._idleRotationSpinupTime;
  81982. },
  81983. /**
  81984. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  81985. */
  81986. set: function (time) {
  81987. this._idleRotationSpinupTime = time;
  81988. },
  81989. enumerable: true,
  81990. configurable: true
  81991. });
  81992. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  81993. /**
  81994. * Gets a value indicating if the camera is currently rotating because of this behavior
  81995. */
  81996. get: function () {
  81997. return Math.abs(this._cameraRotationSpeed) > 0;
  81998. },
  81999. enumerable: true,
  82000. configurable: true
  82001. });
  82002. AutoRotationBehavior.prototype.init = function () {
  82003. // Do notihng
  82004. };
  82005. AutoRotationBehavior.prototype.attach = function (camera) {
  82006. var _this = this;
  82007. this._attachedCamera = camera;
  82008. var scene = this._attachedCamera.getScene();
  82009. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  82010. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  82011. _this._isPointerDown = true;
  82012. return;
  82013. }
  82014. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  82015. _this._isPointerDown = false;
  82016. }
  82017. });
  82018. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  82019. var now = BABYLON.Tools.Now;
  82020. var dt = 0;
  82021. if (_this._lastFrameTime != null) {
  82022. dt = now - _this._lastFrameTime;
  82023. }
  82024. _this._lastFrameTime = now;
  82025. // Stop the animation if there is user interaction and the animation should stop for this interaction
  82026. _this._applyUserInteraction();
  82027. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  82028. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  82029. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  82030. // Step camera rotation by rotation speed
  82031. if (_this._attachedCamera) {
  82032. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  82033. }
  82034. });
  82035. };
  82036. AutoRotationBehavior.prototype.detach = function () {
  82037. if (!this._attachedCamera) {
  82038. return;
  82039. }
  82040. var scene = this._attachedCamera.getScene();
  82041. if (this._onPrePointerObservableObserver) {
  82042. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  82043. }
  82044. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  82045. this._attachedCamera = null;
  82046. };
  82047. /**
  82048. * Returns true if user is scrolling.
  82049. * @return true if user is scrolling.
  82050. */
  82051. AutoRotationBehavior.prototype._userIsZooming = function () {
  82052. if (!this._attachedCamera) {
  82053. return false;
  82054. }
  82055. return this._attachedCamera.inertialRadiusOffset !== 0;
  82056. };
  82057. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  82058. if (!this._attachedCamera) {
  82059. return false;
  82060. }
  82061. var zoomHasHitLimit = false;
  82062. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  82063. zoomHasHitLimit = true;
  82064. }
  82065. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  82066. this._lastFrameRadius = this._attachedCamera.radius;
  82067. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  82068. };
  82069. /**
  82070. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  82071. */
  82072. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  82073. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  82074. this._lastInteractionTime = BABYLON.Tools.Now;
  82075. }
  82076. };
  82077. // Tools
  82078. AutoRotationBehavior.prototype._userIsMoving = function () {
  82079. if (!this._attachedCamera) {
  82080. return false;
  82081. }
  82082. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  82083. this._attachedCamera.inertialBetaOffset !== 0 ||
  82084. this._attachedCamera.inertialRadiusOffset !== 0 ||
  82085. this._attachedCamera.inertialPanningX !== 0 ||
  82086. this._attachedCamera.inertialPanningY !== 0 ||
  82087. this._isPointerDown;
  82088. };
  82089. return AutoRotationBehavior;
  82090. }());
  82091. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  82092. })(BABYLON || (BABYLON = {}));
  82093. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  82094. var BABYLON;
  82095. (function (BABYLON) {
  82096. /**
  82097. * This class can be used to get instrumentation data from a Babylon engine
  82098. */
  82099. var EngineInstrumentation = /** @class */ (function () {
  82100. function EngineInstrumentation(engine) {
  82101. this.engine = engine;
  82102. this._captureGPUFrameTime = false;
  82103. this._gpuFrameTime = new BABYLON.PerfCounter();
  82104. this._captureShaderCompilationTime = false;
  82105. this._shaderCompilationTime = new BABYLON.PerfCounter();
  82106. // Observers
  82107. this._onBeginFrameObserver = null;
  82108. this._onEndFrameObserver = null;
  82109. this._onBeforeShaderCompilationObserver = null;
  82110. this._onAfterShaderCompilationObserver = null;
  82111. }
  82112. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  82113. // Properties
  82114. /**
  82115. * Gets the perf counter used for GPU frame time
  82116. */
  82117. get: function () {
  82118. return this._gpuFrameTime;
  82119. },
  82120. enumerable: true,
  82121. configurable: true
  82122. });
  82123. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  82124. /**
  82125. * Gets the GPU frame time capture status
  82126. */
  82127. get: function () {
  82128. return this._captureGPUFrameTime;
  82129. },
  82130. /**
  82131. * Enable or disable the GPU frame time capture
  82132. */
  82133. set: function (value) {
  82134. var _this = this;
  82135. if (value === this._captureGPUFrameTime) {
  82136. return;
  82137. }
  82138. this._captureGPUFrameTime = value;
  82139. if (value) {
  82140. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  82141. if (!_this._gpuFrameTimeToken) {
  82142. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  82143. }
  82144. });
  82145. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  82146. if (!_this._gpuFrameTimeToken) {
  82147. return;
  82148. }
  82149. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  82150. if (time > -1) {
  82151. _this._gpuFrameTimeToken = null;
  82152. _this._gpuFrameTime.fetchNewFrame();
  82153. _this._gpuFrameTime.addCount(time, true);
  82154. }
  82155. });
  82156. }
  82157. else {
  82158. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  82159. this._onBeginFrameObserver = null;
  82160. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  82161. this._onEndFrameObserver = null;
  82162. }
  82163. },
  82164. enumerable: true,
  82165. configurable: true
  82166. });
  82167. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  82168. /**
  82169. * Gets the perf counter used for shader compilation time
  82170. */
  82171. get: function () {
  82172. return this._shaderCompilationTime;
  82173. },
  82174. enumerable: true,
  82175. configurable: true
  82176. });
  82177. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  82178. /**
  82179. * Gets the shader compilation time capture status
  82180. */
  82181. get: function () {
  82182. return this._captureShaderCompilationTime;
  82183. },
  82184. /**
  82185. * Enable or disable the shader compilation time capture
  82186. */
  82187. set: function (value) {
  82188. var _this = this;
  82189. if (value === this._captureShaderCompilationTime) {
  82190. return;
  82191. }
  82192. this._captureShaderCompilationTime = value;
  82193. if (value) {
  82194. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  82195. _this._shaderCompilationTime.fetchNewFrame();
  82196. _this._shaderCompilationTime.beginMonitoring();
  82197. });
  82198. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  82199. _this._shaderCompilationTime.endMonitoring();
  82200. });
  82201. }
  82202. else {
  82203. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  82204. this._onBeforeShaderCompilationObserver = null;
  82205. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  82206. this._onAfterShaderCompilationObserver = null;
  82207. }
  82208. },
  82209. enumerable: true,
  82210. configurable: true
  82211. });
  82212. EngineInstrumentation.prototype.dispose = function () {
  82213. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  82214. this._onBeginFrameObserver = null;
  82215. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  82216. this._onEndFrameObserver = null;
  82217. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  82218. this._onBeforeShaderCompilationObserver = null;
  82219. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  82220. this._onAfterShaderCompilationObserver = null;
  82221. this.engine = null;
  82222. };
  82223. return EngineInstrumentation;
  82224. }());
  82225. BABYLON.EngineInstrumentation = EngineInstrumentation;
  82226. })(BABYLON || (BABYLON = {}));
  82227. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  82228. var BABYLON;
  82229. (function (BABYLON) {
  82230. /**
  82231. * This class can be used to get instrumentation data from a Babylon engine
  82232. */
  82233. var SceneInstrumentation = /** @class */ (function () {
  82234. function SceneInstrumentation(scene) {
  82235. var _this = this;
  82236. this.scene = scene;
  82237. this._captureActiveMeshesEvaluationTime = false;
  82238. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  82239. this._captureRenderTargetsRenderTime = false;
  82240. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  82241. this._captureFrameTime = false;
  82242. this._frameTime = new BABYLON.PerfCounter();
  82243. this._captureRenderTime = false;
  82244. this._renderTime = new BABYLON.PerfCounter();
  82245. this._captureInterFrameTime = false;
  82246. this._interFrameTime = new BABYLON.PerfCounter();
  82247. this._captureParticlesRenderTime = false;
  82248. this._particlesRenderTime = new BABYLON.PerfCounter();
  82249. this._captureSpritesRenderTime = false;
  82250. this._spritesRenderTime = new BABYLON.PerfCounter();
  82251. this._capturePhysicsTime = false;
  82252. this._physicsTime = new BABYLON.PerfCounter();
  82253. this._captureAnimationsTime = false;
  82254. this._animationsTime = new BABYLON.PerfCounter();
  82255. // Observers
  82256. this._onBeforeActiveMeshesEvaluationObserver = null;
  82257. this._onAfterActiveMeshesEvaluationObserver = null;
  82258. this._onBeforeRenderTargetsRenderObserver = null;
  82259. this._onAfterRenderTargetsRenderObserver = null;
  82260. this._onAfterRenderObserver = null;
  82261. this._onBeforeDrawPhaseObserver = null;
  82262. this._onAfterDrawPhaseObserver = null;
  82263. this._onBeforeAnimationsObserver = null;
  82264. this._onBeforeParticlesRenderingObserver = null;
  82265. this._onAfterParticlesRenderingObserver = null;
  82266. this._onBeforeSpritesRenderingObserver = null;
  82267. this._onAfterSpritesRenderingObserver = null;
  82268. this._onBeforePhysicsObserver = null;
  82269. this._onAfterPhysicsObserver = null;
  82270. this._onAfterAnimationsObserver = null;
  82271. // Before render
  82272. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  82273. if (_this._captureActiveMeshesEvaluationTime) {
  82274. _this._activeMeshesEvaluationTime.fetchNewFrame();
  82275. }
  82276. if (_this._captureRenderTargetsRenderTime) {
  82277. _this._renderTargetsRenderTime.fetchNewFrame();
  82278. }
  82279. if (_this._captureFrameTime) {
  82280. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  82281. _this._frameTime.beginMonitoring();
  82282. }
  82283. if (_this._captureInterFrameTime) {
  82284. _this._interFrameTime.endMonitoring();
  82285. }
  82286. if (_this._captureParticlesRenderTime) {
  82287. _this._particlesRenderTime.fetchNewFrame();
  82288. }
  82289. if (_this._captureSpritesRenderTime) {
  82290. _this._spritesRenderTime.fetchNewFrame();
  82291. }
  82292. if (_this._captureAnimationsTime) {
  82293. _this._animationsTime.beginMonitoring();
  82294. }
  82295. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  82296. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  82297. });
  82298. // After render
  82299. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  82300. if (_this._captureFrameTime) {
  82301. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  82302. _this._frameTime.endMonitoring();
  82303. }
  82304. if (_this._captureRenderTime) {
  82305. _this._renderTime.endMonitoring(false);
  82306. }
  82307. if (_this._captureInterFrameTime) {
  82308. _this._interFrameTime.beginMonitoring();
  82309. }
  82310. });
  82311. }
  82312. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  82313. // Properties
  82314. /**
  82315. * Gets the perf counter used for active meshes evaluation time
  82316. */
  82317. get: function () {
  82318. return this._activeMeshesEvaluationTime;
  82319. },
  82320. enumerable: true,
  82321. configurable: true
  82322. });
  82323. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  82324. /**
  82325. * Gets the active meshes evaluation time capture status
  82326. */
  82327. get: function () {
  82328. return this._captureActiveMeshesEvaluationTime;
  82329. },
  82330. /**
  82331. * Enable or disable the active meshes evaluation time capture
  82332. */
  82333. set: function (value) {
  82334. var _this = this;
  82335. if (value === this._captureActiveMeshesEvaluationTime) {
  82336. return;
  82337. }
  82338. this._captureActiveMeshesEvaluationTime = value;
  82339. if (value) {
  82340. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  82341. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  82342. _this._activeMeshesEvaluationTime.beginMonitoring();
  82343. });
  82344. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  82345. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  82346. _this._activeMeshesEvaluationTime.endMonitoring();
  82347. });
  82348. }
  82349. else {
  82350. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  82351. this._onBeforeActiveMeshesEvaluationObserver = null;
  82352. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  82353. this._onAfterActiveMeshesEvaluationObserver = null;
  82354. }
  82355. },
  82356. enumerable: true,
  82357. configurable: true
  82358. });
  82359. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  82360. /**
  82361. * Gets the perf counter used for render targets render time
  82362. */
  82363. get: function () {
  82364. return this._renderTargetsRenderTime;
  82365. },
  82366. enumerable: true,
  82367. configurable: true
  82368. });
  82369. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  82370. /**
  82371. * Gets the render targets render time capture status
  82372. */
  82373. get: function () {
  82374. return this._captureRenderTargetsRenderTime;
  82375. },
  82376. /**
  82377. * Enable or disable the render targets render time capture
  82378. */
  82379. set: function (value) {
  82380. var _this = this;
  82381. if (value === this._captureRenderTargetsRenderTime) {
  82382. return;
  82383. }
  82384. this._captureRenderTargetsRenderTime = value;
  82385. if (value) {
  82386. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  82387. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  82388. _this._renderTargetsRenderTime.beginMonitoring();
  82389. });
  82390. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  82391. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  82392. _this._renderTargetsRenderTime.endMonitoring(false);
  82393. });
  82394. }
  82395. else {
  82396. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  82397. this._onBeforeRenderTargetsRenderObserver = null;
  82398. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  82399. this._onAfterRenderTargetsRenderObserver = null;
  82400. }
  82401. },
  82402. enumerable: true,
  82403. configurable: true
  82404. });
  82405. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  82406. /**
  82407. * Gets the perf counter used for particles render time
  82408. */
  82409. get: function () {
  82410. return this._particlesRenderTime;
  82411. },
  82412. enumerable: true,
  82413. configurable: true
  82414. });
  82415. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  82416. /**
  82417. * Gets the particles render time capture status
  82418. */
  82419. get: function () {
  82420. return this._captureParticlesRenderTime;
  82421. },
  82422. /**
  82423. * Enable or disable the particles render time capture
  82424. */
  82425. set: function (value) {
  82426. var _this = this;
  82427. if (value === this._captureParticlesRenderTime) {
  82428. return;
  82429. }
  82430. this._captureParticlesRenderTime = value;
  82431. if (value) {
  82432. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  82433. BABYLON.Tools.StartPerformanceCounter("Particles");
  82434. _this._particlesRenderTime.beginMonitoring();
  82435. });
  82436. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  82437. BABYLON.Tools.EndPerformanceCounter("Particles");
  82438. _this._particlesRenderTime.endMonitoring(false);
  82439. });
  82440. }
  82441. else {
  82442. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  82443. this._onBeforeParticlesRenderingObserver = null;
  82444. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  82445. this._onAfterParticlesRenderingObserver = null;
  82446. }
  82447. },
  82448. enumerable: true,
  82449. configurable: true
  82450. });
  82451. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  82452. /**
  82453. * Gets the perf counter used for sprites render time
  82454. */
  82455. get: function () {
  82456. return this._spritesRenderTime;
  82457. },
  82458. enumerable: true,
  82459. configurable: true
  82460. });
  82461. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  82462. /**
  82463. * Gets the sprites render time capture status
  82464. */
  82465. get: function () {
  82466. return this._captureSpritesRenderTime;
  82467. },
  82468. /**
  82469. * Enable or disable the sprites render time capture
  82470. */
  82471. set: function (value) {
  82472. var _this = this;
  82473. if (value === this._captureSpritesRenderTime) {
  82474. return;
  82475. }
  82476. this._captureSpritesRenderTime = value;
  82477. if (value) {
  82478. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  82479. BABYLON.Tools.StartPerformanceCounter("Sprites");
  82480. _this._spritesRenderTime.beginMonitoring();
  82481. });
  82482. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  82483. BABYLON.Tools.EndPerformanceCounter("Sprites");
  82484. _this._spritesRenderTime.endMonitoring(false);
  82485. });
  82486. }
  82487. else {
  82488. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  82489. this._onBeforeSpritesRenderingObserver = null;
  82490. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  82491. this._onAfterSpritesRenderingObserver = null;
  82492. }
  82493. },
  82494. enumerable: true,
  82495. configurable: true
  82496. });
  82497. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  82498. /**
  82499. * Gets the perf counter used for physics time
  82500. */
  82501. get: function () {
  82502. return this._physicsTime;
  82503. },
  82504. enumerable: true,
  82505. configurable: true
  82506. });
  82507. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  82508. /**
  82509. * Gets the physics time capture status
  82510. */
  82511. get: function () {
  82512. return this._capturePhysicsTime;
  82513. },
  82514. /**
  82515. * Enable or disable the physics time capture
  82516. */
  82517. set: function (value) {
  82518. var _this = this;
  82519. if (value === this._capturePhysicsTime) {
  82520. return;
  82521. }
  82522. this._capturePhysicsTime = value;
  82523. if (value) {
  82524. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  82525. BABYLON.Tools.StartPerformanceCounter("Physics");
  82526. _this._physicsTime.beginMonitoring();
  82527. });
  82528. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  82529. BABYLON.Tools.EndPerformanceCounter("Physics");
  82530. _this._physicsTime.endMonitoring();
  82531. });
  82532. }
  82533. else {
  82534. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  82535. this._onBeforePhysicsObserver = null;
  82536. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  82537. this._onAfterPhysicsObserver = null;
  82538. }
  82539. },
  82540. enumerable: true,
  82541. configurable: true
  82542. });
  82543. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  82544. /**
  82545. * Gets the perf counter used for animations time
  82546. */
  82547. get: function () {
  82548. return this._animationsTime;
  82549. },
  82550. enumerable: true,
  82551. configurable: true
  82552. });
  82553. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  82554. /**
  82555. * Gets the animations time capture status
  82556. */
  82557. get: function () {
  82558. return this._captureAnimationsTime;
  82559. },
  82560. /**
  82561. * Enable or disable the animations time capture
  82562. */
  82563. set: function (value) {
  82564. var _this = this;
  82565. if (value === this._captureAnimationsTime) {
  82566. return;
  82567. }
  82568. this._captureAnimationsTime = value;
  82569. if (value) {
  82570. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  82571. _this._animationsTime.endMonitoring();
  82572. });
  82573. }
  82574. else {
  82575. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  82576. this._onAfterAnimationsObserver = null;
  82577. }
  82578. },
  82579. enumerable: true,
  82580. configurable: true
  82581. });
  82582. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  82583. /**
  82584. * Gets the perf counter used for frame time capture
  82585. */
  82586. get: function () {
  82587. return this._frameTime;
  82588. },
  82589. enumerable: true,
  82590. configurable: true
  82591. });
  82592. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  82593. /**
  82594. * Gets the frame time capture status
  82595. */
  82596. get: function () {
  82597. return this._captureFrameTime;
  82598. },
  82599. /**
  82600. * Enable or disable the frame time capture
  82601. */
  82602. set: function (value) {
  82603. this._captureFrameTime = value;
  82604. },
  82605. enumerable: true,
  82606. configurable: true
  82607. });
  82608. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  82609. /**
  82610. * Gets the perf counter used for inter-frames time capture
  82611. */
  82612. get: function () {
  82613. return this._interFrameTime;
  82614. },
  82615. enumerable: true,
  82616. configurable: true
  82617. });
  82618. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  82619. /**
  82620. * Gets the inter-frames time capture status
  82621. */
  82622. get: function () {
  82623. return this._captureInterFrameTime;
  82624. },
  82625. /**
  82626. * Enable or disable the inter-frames time capture
  82627. */
  82628. set: function (value) {
  82629. this._captureInterFrameTime = value;
  82630. },
  82631. enumerable: true,
  82632. configurable: true
  82633. });
  82634. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  82635. /**
  82636. * Gets the perf counter used for render time capture
  82637. */
  82638. get: function () {
  82639. return this._renderTime;
  82640. },
  82641. enumerable: true,
  82642. configurable: true
  82643. });
  82644. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  82645. /**
  82646. * Gets the render time capture status
  82647. */
  82648. get: function () {
  82649. return this._captureRenderTime;
  82650. },
  82651. /**
  82652. * Enable or disable the render time capture
  82653. */
  82654. set: function (value) {
  82655. var _this = this;
  82656. if (value === this._captureRenderTime) {
  82657. return;
  82658. }
  82659. this._captureRenderTime = value;
  82660. if (value) {
  82661. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  82662. _this._renderTime.beginMonitoring();
  82663. BABYLON.Tools.StartPerformanceCounter("Main render");
  82664. });
  82665. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  82666. _this._renderTime.endMonitoring(false);
  82667. BABYLON.Tools.EndPerformanceCounter("Main render");
  82668. });
  82669. }
  82670. else {
  82671. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  82672. this._onBeforeDrawPhaseObserver = null;
  82673. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  82674. this._onAfterDrawPhaseObserver = null;
  82675. }
  82676. },
  82677. enumerable: true,
  82678. configurable: true
  82679. });
  82680. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  82681. /**
  82682. * Gets the perf counter used for draw calls
  82683. */
  82684. get: function () {
  82685. return this.scene.getEngine()._drawCalls;
  82686. },
  82687. enumerable: true,
  82688. configurable: true
  82689. });
  82690. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  82691. /**
  82692. * Gets the perf counter used for texture collisions
  82693. */
  82694. get: function () {
  82695. return this.scene.getEngine()._textureCollisions;
  82696. },
  82697. enumerable: true,
  82698. configurable: true
  82699. });
  82700. SceneInstrumentation.prototype.dispose = function () {
  82701. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  82702. this._onAfterRenderObserver = null;
  82703. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  82704. this._onBeforeActiveMeshesEvaluationObserver = null;
  82705. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  82706. this._onAfterActiveMeshesEvaluationObserver = null;
  82707. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  82708. this._onBeforeRenderTargetsRenderObserver = null;
  82709. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  82710. this._onAfterRenderTargetsRenderObserver = null;
  82711. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  82712. this._onBeforeAnimationsObserver = null;
  82713. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  82714. this._onBeforeParticlesRenderingObserver = null;
  82715. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  82716. this._onAfterParticlesRenderingObserver = null;
  82717. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  82718. this._onBeforeSpritesRenderingObserver = null;
  82719. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  82720. this._onAfterSpritesRenderingObserver = null;
  82721. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  82722. this._onBeforeDrawPhaseObserver = null;
  82723. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  82724. this._onAfterDrawPhaseObserver = null;
  82725. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  82726. this._onBeforePhysicsObserver = null;
  82727. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  82728. this._onAfterPhysicsObserver = null;
  82729. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  82730. this._onAfterAnimationsObserver = null;
  82731. this.scene = null;
  82732. };
  82733. return SceneInstrumentation;
  82734. }());
  82735. BABYLON.SceneInstrumentation = SceneInstrumentation;
  82736. })(BABYLON || (BABYLON = {}));
  82737. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  82738. var BABYLON;
  82739. (function (BABYLON) {
  82740. var _TimeToken = /** @class */ (function () {
  82741. function _TimeToken() {
  82742. this._timeElapsedQueryEnded = false;
  82743. }
  82744. return _TimeToken;
  82745. }());
  82746. BABYLON._TimeToken = _TimeToken;
  82747. })(BABYLON || (BABYLON = {}));
  82748. //# sourceMappingURL=babylon.timeToken.js.map
  82749. var BABYLON;
  82750. (function (BABYLON) {
  82751. /**
  82752. * Background material defines definition.
  82753. */
  82754. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  82755. __extends(BackgroundMaterialDefines, _super);
  82756. /**
  82757. * Constructor of the defines.
  82758. */
  82759. function BackgroundMaterialDefines() {
  82760. var _this = _super.call(this) || this;
  82761. /**
  82762. * True if the diffuse texture is in use.
  82763. */
  82764. _this.DIFFUSE = false;
  82765. /**
  82766. * The direct UV channel to use.
  82767. */
  82768. _this.DIFFUSEDIRECTUV = 0;
  82769. /**
  82770. * True if the diffuse texture is in gamma space.
  82771. */
  82772. _this.GAMMADIFFUSE = false;
  82773. /**
  82774. * True if the diffuse texture has opacity in the alpha channel.
  82775. */
  82776. _this.DIFFUSEHASALPHA = false;
  82777. /**
  82778. * True if you want the material to fade to transparent at grazing angle.
  82779. */
  82780. _this.OPACITYFRESNEL = false;
  82781. /**
  82782. * True if an extra blur needs to be added in the reflection.
  82783. */
  82784. _this.REFLECTIONBLUR = false;
  82785. /**
  82786. * True if you want the material to fade to reflection at grazing angle.
  82787. */
  82788. _this.REFLECTIONFRESNEL = false;
  82789. /**
  82790. * True if you want the material to falloff as far as you move away from the scene center.
  82791. */
  82792. _this.REFLECTIONFALLOFF = false;
  82793. /**
  82794. * False if the current Webgl implementation does not support the texture lod extension.
  82795. */
  82796. _this.TEXTURELODSUPPORT = false;
  82797. /**
  82798. * True to ensure the data are premultiplied.
  82799. */
  82800. _this.PREMULTIPLYALPHA = false;
  82801. /**
  82802. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  82803. */
  82804. _this.USERGBCOLOR = false;
  82805. /**
  82806. * True to add noise in order to reduce the banding effect.
  82807. */
  82808. _this.NOISE = false;
  82809. // Image Processing Configuration.
  82810. _this.IMAGEPROCESSING = false;
  82811. _this.VIGNETTE = false;
  82812. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  82813. _this.VIGNETTEBLENDMODEOPAQUE = false;
  82814. _this.TONEMAPPING = false;
  82815. _this.CONTRAST = false;
  82816. _this.COLORCURVES = false;
  82817. _this.COLORGRADING = false;
  82818. _this.COLORGRADING3D = false;
  82819. _this.SAMPLER3DGREENDEPTH = false;
  82820. _this.SAMPLER3DBGRMAP = false;
  82821. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  82822. _this.EXPOSURE = false;
  82823. // Reflection.
  82824. _this.REFLECTION = false;
  82825. _this.REFLECTIONMAP_3D = false;
  82826. _this.REFLECTIONMAP_SPHERICAL = false;
  82827. _this.REFLECTIONMAP_PLANAR = false;
  82828. _this.REFLECTIONMAP_CUBIC = false;
  82829. _this.REFLECTIONMAP_PROJECTION = false;
  82830. _this.REFLECTIONMAP_SKYBOX = false;
  82831. _this.REFLECTIONMAP_EXPLICIT = false;
  82832. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  82833. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  82834. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  82835. _this.INVERTCUBICMAP = false;
  82836. _this.REFLECTIONMAP_OPPOSITEZ = false;
  82837. _this.LODINREFLECTIONALPHA = false;
  82838. _this.GAMMAREFLECTION = false;
  82839. // Default BJS.
  82840. _this.MAINUV1 = false;
  82841. _this.MAINUV2 = false;
  82842. _this.UV1 = false;
  82843. _this.UV2 = false;
  82844. _this.CLIPPLANE = false;
  82845. _this.POINTSIZE = false;
  82846. _this.FOG = false;
  82847. _this.NORMAL = false;
  82848. _this.NUM_BONE_INFLUENCERS = 0;
  82849. _this.BonesPerMesh = 0;
  82850. _this.INSTANCES = false;
  82851. _this.SHADOWFLOAT = false;
  82852. _this.rebuild();
  82853. return _this;
  82854. }
  82855. return BackgroundMaterialDefines;
  82856. }(BABYLON.MaterialDefines));
  82857. /**
  82858. * Background material used to create an efficient environement around your scene.
  82859. */
  82860. var BackgroundMaterial = /** @class */ (function (_super) {
  82861. __extends(BackgroundMaterial, _super);
  82862. /**
  82863. * constructor
  82864. * @param name The name of the material
  82865. * @param scene The scene to add the material to
  82866. */
  82867. function BackgroundMaterial(name, scene) {
  82868. var _this = _super.call(this, name, scene) || this;
  82869. _this.primaryColor = BABYLON.Color3.White();
  82870. _this.primaryLevel = 1;
  82871. _this.secondaryColor = BABYLON.Color3.Gray();
  82872. _this.secondaryLevel = 1;
  82873. _this.tertiaryColor = BABYLON.Color3.Black();
  82874. _this.tertiaryLevel = 1;
  82875. _this.reflectionTexture = null;
  82876. _this.reflectionBlur = 0;
  82877. _this.diffuseTexture = null;
  82878. /**
  82879. * Specify the list of lights casting shadow on the material.
  82880. * All scene shadow lights will be included if null.
  82881. */
  82882. _this._shadowLights = null;
  82883. _this.shadowLights = null;
  82884. _this.shadowBlurScale = 1;
  82885. _this.shadowLevel = 0;
  82886. _this.sceneCenter = BABYLON.Vector3.Zero();
  82887. _this.opacityFresnel = true;
  82888. _this.reflectionFresnel = false;
  82889. _this.reflectionFalloffDistance = 0.0;
  82890. _this.reflectionAmount = 1.0;
  82891. _this.reflectionReflectance0 = 0.05;
  82892. _this.reflectionReflectance90 = 0.5;
  82893. _this.useRGBColor = true;
  82894. _this.enableNoise = false;
  82895. /**
  82896. * Number of Simultaneous lights allowed on the material.
  82897. */
  82898. _this._maxSimultaneousLights = 4;
  82899. _this.maxSimultaneousLights = 4;
  82900. /**
  82901. * Keep track of the image processing observer to allow dispose and replace.
  82902. */
  82903. _this._imageProcessingObserver = null;
  82904. // Temp values kept as cache in the material.
  82905. _this._renderTargets = new BABYLON.SmartArray(16);
  82906. _this._reflectionControls = BABYLON.Vector4.Zero();
  82907. // Setup the default processing configuration to the scene.
  82908. _this._attachImageProcessingConfiguration(null);
  82909. _this.getRenderTargetTextures = function () {
  82910. _this._renderTargets.reset();
  82911. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  82912. _this._renderTargets.push(_this._diffuseTexture);
  82913. }
  82914. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  82915. _this._renderTargets.push(_this._reflectionTexture);
  82916. }
  82917. return _this._renderTargets;
  82918. };
  82919. return _this;
  82920. }
  82921. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  82922. /**
  82923. * Sets the reflection reflectance fresnel values according to the default standard
  82924. * empirically know to work well :-)
  82925. */
  82926. set: function (value) {
  82927. var reflectionWeight = value;
  82928. if (reflectionWeight < 0.5) {
  82929. reflectionWeight = reflectionWeight * 2.0;
  82930. this.reflectionReflectance0 = BackgroundMaterial.standardReflectance0 * reflectionWeight;
  82931. this.reflectionReflectance90 = BackgroundMaterial.standardReflectance90 * reflectionWeight;
  82932. }
  82933. else {
  82934. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  82935. this.reflectionReflectance0 = BackgroundMaterial.standardReflectance0 + (1.0 - BackgroundMaterial.standardReflectance0) * reflectionWeight;
  82936. this.reflectionReflectance90 = BackgroundMaterial.standardReflectance90 + (1.0 - BackgroundMaterial.standardReflectance90) * reflectionWeight;
  82937. }
  82938. },
  82939. enumerable: true,
  82940. configurable: true
  82941. });
  82942. /**
  82943. * Attaches a new image processing configuration to the PBR Material.
  82944. * @param configuration (if null the scene configuration will be use)
  82945. */
  82946. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  82947. var _this = this;
  82948. if (configuration === this._imageProcessingConfiguration) {
  82949. return;
  82950. }
  82951. // Detaches observer.
  82952. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  82953. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  82954. }
  82955. // Pick the scene configuration if needed.
  82956. if (!configuration) {
  82957. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  82958. }
  82959. else {
  82960. this._imageProcessingConfiguration = configuration;
  82961. }
  82962. // Attaches observer.
  82963. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  82964. _this._markAllSubMeshesAsImageProcessingDirty();
  82965. });
  82966. };
  82967. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  82968. /**
  82969. * Gets the image processing configuration used either in this material.
  82970. */
  82971. get: function () {
  82972. return this._imageProcessingConfiguration;
  82973. },
  82974. /**
  82975. * Sets the Default image processing configuration used either in the this material.
  82976. *
  82977. * If sets to null, the scene one is in use.
  82978. */
  82979. set: function (value) {
  82980. this._attachImageProcessingConfiguration(value);
  82981. // Ensure the effect will be rebuilt.
  82982. this._markAllSubMeshesAsTexturesDirty();
  82983. },
  82984. enumerable: true,
  82985. configurable: true
  82986. });
  82987. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  82988. /**
  82989. * Gets wether the color curves effect is enabled.
  82990. */
  82991. get: function () {
  82992. return this.imageProcessingConfiguration.colorCurvesEnabled;
  82993. },
  82994. /**
  82995. * Sets wether the color curves effect is enabled.
  82996. */
  82997. set: function (value) {
  82998. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  82999. },
  83000. enumerable: true,
  83001. configurable: true
  83002. });
  83003. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  83004. /**
  83005. * Gets wether the color grading effect is enabled.
  83006. */
  83007. get: function () {
  83008. return this.imageProcessingConfiguration.colorGradingEnabled;
  83009. },
  83010. /**
  83011. * Gets wether the color grading effect is enabled.
  83012. */
  83013. set: function (value) {
  83014. this.imageProcessingConfiguration.colorGradingEnabled = value;
  83015. },
  83016. enumerable: true,
  83017. configurable: true
  83018. });
  83019. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  83020. /**
  83021. * Gets wether tonemapping is enabled or not.
  83022. */
  83023. get: function () {
  83024. return this._imageProcessingConfiguration.toneMappingEnabled;
  83025. },
  83026. /**
  83027. * Sets wether tonemapping is enabled or not
  83028. */
  83029. set: function (value) {
  83030. this._imageProcessingConfiguration.toneMappingEnabled = value;
  83031. },
  83032. enumerable: true,
  83033. configurable: true
  83034. });
  83035. ;
  83036. ;
  83037. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  83038. /**
  83039. * The camera exposure used on this material.
  83040. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  83041. * This corresponds to a photographic exposure.
  83042. */
  83043. get: function () {
  83044. return this._imageProcessingConfiguration.exposure;
  83045. },
  83046. /**
  83047. * The camera exposure used on this material.
  83048. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  83049. * This corresponds to a photographic exposure.
  83050. */
  83051. set: function (value) {
  83052. this._imageProcessingConfiguration.exposure = value;
  83053. },
  83054. enumerable: true,
  83055. configurable: true
  83056. });
  83057. ;
  83058. ;
  83059. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  83060. /**
  83061. * Gets The camera contrast used on this material.
  83062. */
  83063. get: function () {
  83064. return this._imageProcessingConfiguration.contrast;
  83065. },
  83066. /**
  83067. * Sets The camera contrast used on this material.
  83068. */
  83069. set: function (value) {
  83070. this._imageProcessingConfiguration.contrast = value;
  83071. },
  83072. enumerable: true,
  83073. configurable: true
  83074. });
  83075. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  83076. /**
  83077. * Gets the Color Grading 2D Lookup Texture.
  83078. */
  83079. get: function () {
  83080. return this._imageProcessingConfiguration.colorGradingTexture;
  83081. },
  83082. /**
  83083. * Sets the Color Grading 2D Lookup Texture.
  83084. */
  83085. set: function (value) {
  83086. this.imageProcessingConfiguration.colorGradingTexture = value;
  83087. },
  83088. enumerable: true,
  83089. configurable: true
  83090. });
  83091. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  83092. /**
  83093. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  83094. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  83095. * 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;
  83096. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  83097. */
  83098. get: function () {
  83099. return this.imageProcessingConfiguration.colorCurves;
  83100. },
  83101. /**
  83102. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  83103. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  83104. * 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;
  83105. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  83106. */
  83107. set: function (value) {
  83108. this.imageProcessingConfiguration.colorCurves = value;
  83109. },
  83110. enumerable: true,
  83111. configurable: true
  83112. });
  83113. /**
  83114. * The entire material has been created in order to prevent overdraw.
  83115. * @returns false
  83116. */
  83117. BackgroundMaterial.prototype.needAlphaTesting = function () {
  83118. return true;
  83119. };
  83120. /**
  83121. * The entire material has been created in order to prevent overdraw.
  83122. * @returns true if blending is enable
  83123. */
  83124. BackgroundMaterial.prototype.needAlphaBlending = function () {
  83125. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  83126. };
  83127. /**
  83128. * Checks wether the material is ready to be rendered for a given mesh.
  83129. * @param mesh The mesh to render
  83130. * @param subMesh The submesh to check against
  83131. * @param useInstances Specify wether or not the material is used with instances
  83132. */
  83133. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  83134. var _this = this;
  83135. if (useInstances === void 0) { useInstances = false; }
  83136. if (subMesh.effect && this.isFrozen) {
  83137. if (this._wasPreviouslyReady) {
  83138. return true;
  83139. }
  83140. }
  83141. if (!subMesh._materialDefines) {
  83142. subMesh._materialDefines = new BackgroundMaterialDefines();
  83143. }
  83144. var scene = this.getScene();
  83145. var defines = subMesh._materialDefines;
  83146. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  83147. if (defines._renderId === scene.getRenderId()) {
  83148. return true;
  83149. }
  83150. }
  83151. var engine = scene.getEngine();
  83152. // Lights
  83153. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  83154. defines._needNormals = true;
  83155. // Textures
  83156. if (defines._areTexturesDirty) {
  83157. defines._needUVs = false;
  83158. if (scene.texturesEnabled) {
  83159. if (scene.getEngine().getCaps().textureLOD) {
  83160. defines.TEXTURELODSUPPORT = true;
  83161. }
  83162. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  83163. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  83164. return false;
  83165. }
  83166. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  83167. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  83168. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  83169. defines.OPACITYFRESNEL = this._opacityFresnel;
  83170. }
  83171. else {
  83172. defines.DIFFUSE = false;
  83173. defines.DIFFUSEHASALPHA = false;
  83174. defines.GAMMADIFFUSE = false;
  83175. defines.OPACITYFRESNEL = false;
  83176. }
  83177. var reflectionTexture = this._reflectionTexture;
  83178. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  83179. if (!reflectionTexture.isReadyOrNotBlocking()) {
  83180. return false;
  83181. }
  83182. defines.REFLECTION = true;
  83183. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  83184. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  83185. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  83186. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  83187. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  83188. defines.INVERTCUBICMAP = true;
  83189. }
  83190. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  83191. switch (reflectionTexture.coordinatesMode) {
  83192. case BABYLON.Texture.CUBIC_MODE:
  83193. case BABYLON.Texture.INVCUBIC_MODE:
  83194. defines.REFLECTIONMAP_CUBIC = true;
  83195. break;
  83196. case BABYLON.Texture.EXPLICIT_MODE:
  83197. defines.REFLECTIONMAP_EXPLICIT = true;
  83198. break;
  83199. case BABYLON.Texture.PLANAR_MODE:
  83200. defines.REFLECTIONMAP_PLANAR = true;
  83201. break;
  83202. case BABYLON.Texture.PROJECTION_MODE:
  83203. defines.REFLECTIONMAP_PROJECTION = true;
  83204. break;
  83205. case BABYLON.Texture.SKYBOX_MODE:
  83206. defines.REFLECTIONMAP_SKYBOX = true;
  83207. break;
  83208. case BABYLON.Texture.SPHERICAL_MODE:
  83209. defines.REFLECTIONMAP_SPHERICAL = true;
  83210. break;
  83211. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  83212. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  83213. break;
  83214. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  83215. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  83216. break;
  83217. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  83218. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  83219. break;
  83220. }
  83221. if (this.reflectionFresnel) {
  83222. defines.REFLECTIONFRESNEL = true;
  83223. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  83224. this._reflectionControls.x = this.reflectionAmount;
  83225. this._reflectionControls.y = this.reflectionReflectance0;
  83226. this._reflectionControls.z = this.reflectionReflectance90;
  83227. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  83228. }
  83229. else {
  83230. defines.REFLECTIONFRESNEL = false;
  83231. defines.REFLECTIONFALLOFF = false;
  83232. }
  83233. }
  83234. else {
  83235. defines.REFLECTION = false;
  83236. defines.REFLECTIONFALLOFF = false;
  83237. defines.REFLECTIONBLUR = false;
  83238. defines.REFLECTIONMAP_3D = false;
  83239. defines.REFLECTIONMAP_SPHERICAL = false;
  83240. defines.REFLECTIONMAP_PLANAR = false;
  83241. defines.REFLECTIONMAP_CUBIC = false;
  83242. defines.REFLECTIONMAP_PROJECTION = false;
  83243. defines.REFLECTIONMAP_SKYBOX = false;
  83244. defines.REFLECTIONMAP_EXPLICIT = false;
  83245. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  83246. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  83247. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  83248. defines.INVERTCUBICMAP = false;
  83249. defines.REFLECTIONMAP_OPPOSITEZ = false;
  83250. defines.LODINREFLECTIONALPHA = false;
  83251. defines.GAMMAREFLECTION = false;
  83252. }
  83253. }
  83254. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  83255. defines.USERGBCOLOR = this._useRGBColor;
  83256. defines.NOISE = this._enableNoise;
  83257. }
  83258. if (defines._areImageProcessingDirty) {
  83259. if (!this._imageProcessingConfiguration.isReady()) {
  83260. return false;
  83261. }
  83262. this._imageProcessingConfiguration.prepareDefines(defines);
  83263. }
  83264. // Misc.
  83265. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  83266. // Values that need to be evaluated on every frame
  83267. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  83268. // Attribs
  83269. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  83270. if (mesh) {
  83271. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  83272. mesh.createNormals(true);
  83273. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  83274. }
  83275. }
  83276. }
  83277. // Get correct effect
  83278. if (defines.isDirty) {
  83279. defines.markAsProcessed();
  83280. scene.resetCachedMaterial();
  83281. // Fallbacks
  83282. var fallbacks = new BABYLON.EffectFallbacks();
  83283. if (defines.FOG) {
  83284. fallbacks.addFallback(0, "FOG");
  83285. }
  83286. if (defines.POINTSIZE) {
  83287. fallbacks.addFallback(1, "POINTSIZE");
  83288. }
  83289. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  83290. if (defines.NUM_BONE_INFLUENCERS > 0) {
  83291. fallbacks.addCPUSkinningFallback(0, mesh);
  83292. }
  83293. //Attributes
  83294. var attribs = [BABYLON.VertexBuffer.PositionKind];
  83295. if (defines.NORMAL) {
  83296. attribs.push(BABYLON.VertexBuffer.NormalKind);
  83297. }
  83298. if (defines.UV1) {
  83299. attribs.push(BABYLON.VertexBuffer.UVKind);
  83300. }
  83301. if (defines.UV2) {
  83302. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  83303. }
  83304. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  83305. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  83306. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  83307. "vFogInfos", "vFogColor", "pointSize",
  83308. "vClipPlane", "mBones",
  83309. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  83310. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos",
  83311. "shadowLevel", "alpha",
  83312. "vBackgroundCenter", "vReflectionControl",
  83313. "vDiffuseInfos", "diffuseMatrix",
  83314. ];
  83315. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  83316. var uniformBuffers = ["Material", "Scene"];
  83317. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  83318. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  83319. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  83320. uniformsNames: uniforms,
  83321. uniformBuffersNames: uniformBuffers,
  83322. samplers: samplers,
  83323. defines: defines,
  83324. maxSimultaneousLights: this._maxSimultaneousLights
  83325. });
  83326. var onCompiled = function (effect) {
  83327. if (_this.onCompiled) {
  83328. _this.onCompiled(effect);
  83329. }
  83330. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  83331. };
  83332. var join = defines.toString();
  83333. subMesh.setEffect(scene.getEngine().createEffect("background", {
  83334. attributes: attribs,
  83335. uniformsNames: uniforms,
  83336. uniformBuffersNames: uniformBuffers,
  83337. samplers: samplers,
  83338. defines: join,
  83339. fallbacks: fallbacks,
  83340. onCompiled: onCompiled,
  83341. onError: this.onError,
  83342. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  83343. }, engine), defines);
  83344. this.buildUniformLayout();
  83345. }
  83346. if (!subMesh.effect || !subMesh.effect.isReady()) {
  83347. return false;
  83348. }
  83349. defines._renderId = scene.getRenderId();
  83350. this._wasPreviouslyReady = true;
  83351. return true;
  83352. };
  83353. /**
  83354. * Build the uniform buffer used in the material.
  83355. */
  83356. BackgroundMaterial.prototype.buildUniformLayout = function () {
  83357. // Order is important !
  83358. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  83359. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  83360. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  83361. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  83362. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  83363. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  83364. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  83365. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  83366. this._uniformBuffer.addUniform("pointSize", 1);
  83367. this._uniformBuffer.addUniform("shadowLevel", 1);
  83368. this._uniformBuffer.addUniform("alpha", 1);
  83369. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  83370. this._uniformBuffer.addUniform("vReflectionControl", 4);
  83371. this._uniformBuffer.create();
  83372. };
  83373. /**
  83374. * Unbind the material.
  83375. */
  83376. BackgroundMaterial.prototype.unbind = function () {
  83377. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  83378. this._uniformBuffer.setTexture("diffuseSampler", null);
  83379. }
  83380. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  83381. this._uniformBuffer.setTexture("reflectionSampler", null);
  83382. }
  83383. _super.prototype.unbind.call(this);
  83384. };
  83385. /**
  83386. * Bind only the world matrix to the material.
  83387. * @param world The world matrix to bind.
  83388. */
  83389. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  83390. this._activeEffect.setMatrix("world", world);
  83391. };
  83392. /**
  83393. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  83394. * @param world The world matrix to bind.
  83395. * @param subMesh The submesh to bind for.
  83396. */
  83397. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  83398. var scene = this.getScene();
  83399. var defines = subMesh._materialDefines;
  83400. if (!defines) {
  83401. return;
  83402. }
  83403. var effect = subMesh.effect;
  83404. if (!effect) {
  83405. return;
  83406. }
  83407. this._activeEffect = effect;
  83408. // Matrices
  83409. this.bindOnlyWorldMatrix(world);
  83410. // Bones
  83411. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  83412. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  83413. if (mustRebind) {
  83414. this._uniformBuffer.bindToEffect(effect, "Material");
  83415. this.bindViewProjection(effect);
  83416. var reflectionTexture = this._reflectionTexture;
  83417. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  83418. // Texture uniforms
  83419. if (scene.texturesEnabled) {
  83420. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  83421. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  83422. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  83423. }
  83424. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  83425. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  83426. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  83427. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  83428. }
  83429. }
  83430. if (this.shadowLevel > 0) {
  83431. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  83432. }
  83433. this._uniformBuffer.updateFloat("alpha", this.alpha);
  83434. // Point size
  83435. if (this.pointsCloud) {
  83436. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  83437. }
  83438. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  83439. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  83440. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  83441. }
  83442. // Textures
  83443. if (scene.texturesEnabled) {
  83444. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  83445. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  83446. }
  83447. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  83448. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  83449. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  83450. }
  83451. else if (!defines.REFLECTIONBLUR) {
  83452. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  83453. }
  83454. else {
  83455. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  83456. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  83457. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  83458. }
  83459. if (defines.REFLECTIONFRESNEL) {
  83460. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  83461. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  83462. }
  83463. }
  83464. }
  83465. // Clip plane
  83466. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  83467. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  83468. }
  83469. if (mustRebind || !this.isFrozen) {
  83470. if (scene.lightsEnabled) {
  83471. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  83472. }
  83473. // View
  83474. this.bindView(effect);
  83475. // Fog
  83476. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  83477. // image processing
  83478. this._imageProcessingConfiguration.bind(this._activeEffect);
  83479. }
  83480. this._uniformBuffer.update();
  83481. this._afterBind(mesh);
  83482. };
  83483. /**
  83484. * Dispose the material.
  83485. * @forceDisposeEffect Force disposal of the associated effect.
  83486. * @forceDisposeTextures Force disposal of the associated textures.
  83487. */
  83488. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  83489. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  83490. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  83491. if (forceDisposeTextures) {
  83492. if (this.diffuseTexture) {
  83493. this.diffuseTexture.dispose();
  83494. }
  83495. if (this.reflectionTexture) {
  83496. this.reflectionTexture.dispose();
  83497. }
  83498. }
  83499. this._renderTargets.dispose();
  83500. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  83501. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  83502. }
  83503. _super.prototype.dispose.call(this, forceDisposeEffect);
  83504. };
  83505. /**
  83506. * Clones the material.
  83507. * @name The cloned name.
  83508. * @returns The cloned material.
  83509. */
  83510. BackgroundMaterial.prototype.clone = function (name) {
  83511. var _this = this;
  83512. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  83513. };
  83514. /**
  83515. * Serializes the current material to its JSON representation.
  83516. * @returns The JSON representation.
  83517. */
  83518. BackgroundMaterial.prototype.serialize = function () {
  83519. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  83520. serializationObject.customType = "BABYLON.BackgroundMaterial";
  83521. return serializationObject;
  83522. };
  83523. /**
  83524. * Gets the class name of the material
  83525. * @returns "BackgroundMaterial"
  83526. */
  83527. BackgroundMaterial.prototype.getClassName = function () {
  83528. return "BackgroundMaterial";
  83529. };
  83530. /**
  83531. * Parse a JSON input to create back a background material.
  83532. * @param source
  83533. * @param scene
  83534. * @param rootUrl
  83535. * @returns the instantiated BackgroundMaterial.
  83536. */
  83537. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  83538. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  83539. };
  83540. /**
  83541. * Standard reflectance value at parallel view angle.
  83542. */
  83543. BackgroundMaterial.standardReflectance0 = 0.05;
  83544. /**
  83545. * Standard reflectance value at grazing angle.
  83546. */
  83547. BackgroundMaterial.standardReflectance90 = 0.5;
  83548. __decorate([
  83549. BABYLON.serializeAsColor3()
  83550. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  83551. __decorate([
  83552. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  83553. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  83554. __decorate([
  83555. BABYLON.serialize()
  83556. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  83557. __decorate([
  83558. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  83559. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  83560. __decorate([
  83561. BABYLON.serializeAsColor3()
  83562. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  83563. __decorate([
  83564. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  83565. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  83566. __decorate([
  83567. BABYLON.serialize()
  83568. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  83569. __decorate([
  83570. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  83571. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  83572. __decorate([
  83573. BABYLON.serializeAsColor3()
  83574. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  83575. __decorate([
  83576. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  83577. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  83578. __decorate([
  83579. BABYLON.serialize()
  83580. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  83581. __decorate([
  83582. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  83583. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  83584. __decorate([
  83585. BABYLON.serializeAsTexture()
  83586. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  83587. __decorate([
  83588. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83589. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  83590. __decorate([
  83591. BABYLON.serialize()
  83592. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  83593. __decorate([
  83594. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83595. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  83596. __decorate([
  83597. BABYLON.serializeAsTexture()
  83598. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  83599. __decorate([
  83600. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83601. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  83602. __decorate([
  83603. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83604. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  83605. __decorate([
  83606. BABYLON.serialize()
  83607. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  83608. __decorate([
  83609. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83610. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  83611. __decorate([
  83612. BABYLON.serialize()
  83613. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  83614. __decorate([
  83615. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83616. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  83617. __decorate([
  83618. BABYLON.serializeAsVector3()
  83619. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  83620. __decorate([
  83621. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83622. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  83623. __decorate([
  83624. BABYLON.serialize()
  83625. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  83626. __decorate([
  83627. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83628. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  83629. __decorate([
  83630. BABYLON.serialize()
  83631. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  83632. __decorate([
  83633. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83634. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  83635. __decorate([
  83636. BABYLON.serialize()
  83637. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  83638. __decorate([
  83639. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83640. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  83641. __decorate([
  83642. BABYLON.serialize()
  83643. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  83644. __decorate([
  83645. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83646. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  83647. __decorate([
  83648. BABYLON.serialize()
  83649. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  83650. __decorate([
  83651. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83652. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  83653. __decorate([
  83654. BABYLON.serialize()
  83655. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  83656. __decorate([
  83657. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83658. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  83659. __decorate([
  83660. BABYLON.serialize()
  83661. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  83662. __decorate([
  83663. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83664. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  83665. __decorate([
  83666. BABYLON.serialize()
  83667. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  83668. __decorate([
  83669. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83670. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  83671. __decorate([
  83672. BABYLON.serialize()
  83673. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  83674. __decorate([
  83675. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83676. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  83677. __decorate([
  83678. BABYLON.serializeAsImageProcessingConfiguration()
  83679. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  83680. return BackgroundMaterial;
  83681. }(BABYLON.PushMaterial));
  83682. BABYLON.BackgroundMaterial = BackgroundMaterial;
  83683. })(BABYLON || (BABYLON = {}));
  83684. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  83685. var __assign = (this && this.__assign) || Object.assign || function(t) {
  83686. for (var s, i = 1, n = arguments.length; i < n; i++) {
  83687. s = arguments[i];
  83688. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  83689. t[p] = s[p];
  83690. }
  83691. return t;
  83692. };
  83693. var BABYLON;
  83694. (function (BABYLON) {
  83695. /**
  83696. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  83697. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  83698. * It also helps with the default setup of your imageProcessing configuration.
  83699. */
  83700. var EnvironmentHelper = /** @class */ (function () {
  83701. /**
  83702. * constructor
  83703. * @param options
  83704. * @param scene The scene to add the material to
  83705. */
  83706. function EnvironmentHelper(options, scene) {
  83707. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  83708. this._scene = scene;
  83709. this._setupBackground();
  83710. this._setupImageProcessing();
  83711. }
  83712. /**
  83713. * Creates the default options for the helper.
  83714. */
  83715. EnvironmentHelper._getDefaultOptions = function () {
  83716. return {
  83717. createGround: true,
  83718. groundSize: 15,
  83719. groundTexture: this._groundTextureCDNUrl,
  83720. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  83721. groundOpacity: 0.9,
  83722. enableGroundShadow: true,
  83723. groundShadowLevel: 0.5,
  83724. enableGroundMirror: false,
  83725. groundMirrorSizeRatio: 0.3,
  83726. groundMirrorBlurKernel: 64,
  83727. groundMirrorAmount: 1,
  83728. groundMirrorFresnelWeight: 1,
  83729. groundMirrorFallOffDistance: 0,
  83730. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  83731. groundYBias: 0.00001,
  83732. createSkybox: true,
  83733. skyboxSize: 20,
  83734. skyboxTexture: this._skyboxTextureCDNUrl,
  83735. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  83736. backgroundYRotation: 0,
  83737. sizeAuto: true,
  83738. rootPosition: BABYLON.Vector3.Zero(),
  83739. setupImageProcessing: true,
  83740. environmentTexture: this._environmentTextureCDNUrl,
  83741. cameraExposure: 0.8,
  83742. cameraContrast: 1.2,
  83743. toneMappingEnabled: true,
  83744. };
  83745. };
  83746. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  83747. /**
  83748. * Gets the root mesh created by the helper.
  83749. */
  83750. get: function () {
  83751. return this._rootMesh;
  83752. },
  83753. enumerable: true,
  83754. configurable: true
  83755. });
  83756. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  83757. /**
  83758. * Gets the skybox created by the helper.
  83759. */
  83760. get: function () {
  83761. return this._skybox;
  83762. },
  83763. enumerable: true,
  83764. configurable: true
  83765. });
  83766. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  83767. /**
  83768. * Gets the skybox texture created by the helper.
  83769. */
  83770. get: function () {
  83771. return this._skyboxTexture;
  83772. },
  83773. enumerable: true,
  83774. configurable: true
  83775. });
  83776. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  83777. /**
  83778. * Gets the skybox material created by the helper.
  83779. */
  83780. get: function () {
  83781. return this._skyboxMaterial;
  83782. },
  83783. enumerable: true,
  83784. configurable: true
  83785. });
  83786. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  83787. /**
  83788. * Gets the ground mesh created by the helper.
  83789. */
  83790. get: function () {
  83791. return this._ground;
  83792. },
  83793. enumerable: true,
  83794. configurable: true
  83795. });
  83796. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  83797. /**
  83798. * Gets the ground texture created by the helper.
  83799. */
  83800. get: function () {
  83801. return this._groundTexture;
  83802. },
  83803. enumerable: true,
  83804. configurable: true
  83805. });
  83806. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  83807. /**
  83808. * Gets the ground mirror created by the helper.
  83809. */
  83810. get: function () {
  83811. return this._groundMirror;
  83812. },
  83813. enumerable: true,
  83814. configurable: true
  83815. });
  83816. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  83817. /**
  83818. * Gets the ground mirror render list to helps pushing the meshes
  83819. * you wish in the ground reflection.
  83820. */
  83821. get: function () {
  83822. if (this._groundMirror) {
  83823. return this._groundMirror.renderList;
  83824. }
  83825. return null;
  83826. },
  83827. enumerable: true,
  83828. configurable: true
  83829. });
  83830. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  83831. /**
  83832. * Gets the ground material created by the helper.
  83833. */
  83834. get: function () {
  83835. return this._groundMaterial;
  83836. },
  83837. enumerable: true,
  83838. configurable: true
  83839. });
  83840. /**
  83841. * Updates the background according to the new options
  83842. * @param options
  83843. */
  83844. EnvironmentHelper.prototype.updateOptions = function (options) {
  83845. var newOptions = __assign({}, this._options, options);
  83846. if (this._ground && !newOptions.createGround) {
  83847. this._ground.dispose();
  83848. this._ground = null;
  83849. }
  83850. if (this._groundMaterial && !newOptions.createGround) {
  83851. this._groundMaterial.dispose();
  83852. this._groundMaterial = null;
  83853. }
  83854. if (this._groundTexture) {
  83855. if (this._options.groundTexture != newOptions.groundTexture) {
  83856. this._groundTexture.dispose();
  83857. this._groundTexture = null;
  83858. }
  83859. }
  83860. if (this._skybox && !newOptions.createSkybox) {
  83861. this._skybox.dispose();
  83862. this._skybox = null;
  83863. }
  83864. if (this._skyboxMaterial && !newOptions.createSkybox) {
  83865. this._skyboxMaterial.dispose();
  83866. this._skyboxMaterial = null;
  83867. }
  83868. if (this._skyboxTexture) {
  83869. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  83870. this._skyboxTexture.dispose();
  83871. this._skyboxTexture = null;
  83872. }
  83873. }
  83874. if (this._groundMirror && !newOptions.enableGroundMirror) {
  83875. this._groundMirror.dispose();
  83876. this._groundMirror = null;
  83877. }
  83878. if (this._scene.environmentTexture) {
  83879. if (this._options.environmentTexture != newOptions.environmentTexture) {
  83880. this._scene.environmentTexture.dispose();
  83881. }
  83882. }
  83883. this._options = newOptions;
  83884. this._setupBackground();
  83885. this._setupImageProcessing();
  83886. };
  83887. /**
  83888. * Sets the primary color of all the available elements.
  83889. * @param color
  83890. */
  83891. EnvironmentHelper.prototype.setMainColor = function (color) {
  83892. if (this.groundMaterial) {
  83893. this.groundMaterial.primaryColor = color;
  83894. }
  83895. if (this.skyboxMaterial) {
  83896. this.skyboxMaterial.primaryColor = color;
  83897. }
  83898. if (this.groundMirror) {
  83899. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  83900. }
  83901. };
  83902. /**
  83903. * Setup the image processing according to the specified options.
  83904. */
  83905. EnvironmentHelper.prototype._setupImageProcessing = function () {
  83906. if (this._options.setupImageProcessing) {
  83907. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  83908. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  83909. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  83910. this._setupEnvironmentTexture();
  83911. }
  83912. };
  83913. /**
  83914. * Setup the environment texture according to the specified options.
  83915. */
  83916. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  83917. if (this._scene.environmentTexture) {
  83918. return;
  83919. }
  83920. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  83921. this._scene.environmentTexture = this._options.environmentTexture;
  83922. return;
  83923. }
  83924. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  83925. this._scene.environmentTexture = environmentTexture;
  83926. };
  83927. /**
  83928. * Setup the background according to the specified options.
  83929. */
  83930. EnvironmentHelper.prototype._setupBackground = function () {
  83931. if (!this._rootMesh) {
  83932. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  83933. }
  83934. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  83935. var sceneSize = this._getSceneSize();
  83936. if (this._options.createGround) {
  83937. this._setupGround(sceneSize);
  83938. this._setupGroundMaterial();
  83939. this._setupGroundDiffuseTexture();
  83940. if (this._options.enableGroundMirror) {
  83941. this._setupGroundMirrorTexture(sceneSize);
  83942. }
  83943. this._setupMirrorInGroundMaterial();
  83944. }
  83945. if (this._options.createSkybox) {
  83946. this._setupSkybox(sceneSize);
  83947. this._setupSkyboxMaterial();
  83948. this._setupSkyboxReflectionTexture();
  83949. }
  83950. this._rootMesh.position.x = sceneSize.rootPosition.x;
  83951. this._rootMesh.position.z = sceneSize.rootPosition.z;
  83952. this._rootMesh.position.y = sceneSize.rootPosition.y;
  83953. };
  83954. /**
  83955. * Get the scene sizes according to the setup.
  83956. */
  83957. EnvironmentHelper.prototype._getSceneSize = function () {
  83958. var groundSize = this._options.groundSize;
  83959. var skyboxSize = this._options.skyboxSize;
  83960. var rootPosition = this._options.rootPosition;
  83961. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  83962. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  83963. }
  83964. var sceneExtends = this._scene.getWorldExtends();
  83965. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  83966. if (this._options.sizeAuto) {
  83967. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  83968. this._scene.activeCamera.upperRadiusLimit) {
  83969. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  83970. skyboxSize = groundSize;
  83971. }
  83972. var sceneDiagonalLenght = sceneDiagonal.length();
  83973. if (sceneDiagonalLenght > groundSize) {
  83974. groundSize = sceneDiagonalLenght * 2;
  83975. skyboxSize = groundSize;
  83976. }
  83977. // 10 % bigger.
  83978. groundSize *= 1.1;
  83979. skyboxSize *= 1.5;
  83980. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  83981. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  83982. }
  83983. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  83984. };
  83985. /**
  83986. * Setup the ground according to the specified options.
  83987. */
  83988. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  83989. var _this = this;
  83990. if (!this._ground) {
  83991. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  83992. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  83993. this._ground.parent = this._rootMesh;
  83994. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  83995. }
  83996. this._ground.receiveShadows = this._options.enableGroundShadow;
  83997. };
  83998. /**
  83999. * Setup the ground material according to the specified options.
  84000. */
  84001. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  84002. if (!this._groundMaterial) {
  84003. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  84004. }
  84005. this._groundMaterial.alpha = this._options.groundOpacity;
  84006. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  84007. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  84008. this._groundMaterial.primaryLevel = 1;
  84009. this._groundMaterial.primaryColor = this._options.groundColor;
  84010. this._groundMaterial.secondaryLevel = 0;
  84011. this._groundMaterial.tertiaryLevel = 0;
  84012. this._groundMaterial.useRGBColor = false;
  84013. this._groundMaterial.enableNoise = true;
  84014. if (this._ground) {
  84015. this._ground.material = this._groundMaterial;
  84016. }
  84017. };
  84018. /**
  84019. * Setup the ground diffuse texture according to the specified options.
  84020. */
  84021. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  84022. if (!this._groundMaterial) {
  84023. return;
  84024. }
  84025. if (this._groundTexture) {
  84026. return;
  84027. }
  84028. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  84029. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  84030. return;
  84031. }
  84032. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene);
  84033. diffuseTexture.gammaSpace = false;
  84034. diffuseTexture.hasAlpha = true;
  84035. this._groundMaterial.diffuseTexture = diffuseTexture;
  84036. };
  84037. /**
  84038. * Setup the ground mirror texture according to the specified options.
  84039. */
  84040. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  84041. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84042. if (!this._groundMirror) {
  84043. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  84044. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  84045. this._groundMirror.anisotropicFilteringLevel = 1;
  84046. this._groundMirror.wrapU = wrapping;
  84047. this._groundMirror.wrapV = wrapping;
  84048. this._groundMirror.gammaSpace = false;
  84049. if (this._groundMirror.renderList) {
  84050. for (var i = 0; i < this._scene.meshes.length; i++) {
  84051. var mesh = this._scene.meshes[i];
  84052. if (mesh !== this._ground &&
  84053. mesh !== this._skybox &&
  84054. mesh !== this._rootMesh) {
  84055. this._groundMirror.renderList.push(mesh);
  84056. }
  84057. }
  84058. }
  84059. }
  84060. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  84061. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  84062. };
  84063. /**
  84064. * Setup the ground to receive the mirror texture.
  84065. */
  84066. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  84067. if (this._groundMaterial) {
  84068. this._groundMaterial.reflectionTexture = this._groundMirror;
  84069. this._groundMaterial.reflectionFresnel = true;
  84070. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  84071. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  84072. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  84073. }
  84074. };
  84075. /**
  84076. * Setup the skybox according to the specified options.
  84077. */
  84078. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  84079. var _this = this;
  84080. if (!this._skybox) {
  84081. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  84082. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  84083. }
  84084. this._skybox.parent = this._rootMesh;
  84085. };
  84086. /**
  84087. * Setup the skybox material according to the specified options.
  84088. */
  84089. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  84090. if (!this._skybox) {
  84091. return;
  84092. }
  84093. if (!this._skyboxMaterial) {
  84094. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  84095. }
  84096. this._skyboxMaterial.useRGBColor = false;
  84097. this._skyboxMaterial.primaryLevel = 1;
  84098. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  84099. this._skyboxMaterial.secondaryLevel = 0;
  84100. this._skyboxMaterial.tertiaryLevel = 0;
  84101. this._skyboxMaterial.enableNoise = true;
  84102. this._skybox.material = this._skyboxMaterial;
  84103. };
  84104. /**
  84105. * Setup the skybox reflection texture according to the specified options.
  84106. */
  84107. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  84108. if (!this._skyboxMaterial) {
  84109. return;
  84110. }
  84111. if (this._skyboxTexture) {
  84112. return;
  84113. }
  84114. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  84115. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  84116. return;
  84117. }
  84118. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene);
  84119. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  84120. this._skyboxTexture.gammaSpace = false;
  84121. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  84122. };
  84123. /**
  84124. * Dispose all the elements created by the Helper.
  84125. */
  84126. EnvironmentHelper.prototype.dispose = function () {
  84127. if (this._groundMaterial) {
  84128. this._groundMaterial.dispose(true, true);
  84129. }
  84130. if (this._skyboxMaterial) {
  84131. this._skyboxMaterial.dispose(true, true);
  84132. }
  84133. this._rootMesh.dispose(false);
  84134. };
  84135. /**
  84136. * Default ground texture URL.
  84137. */
  84138. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  84139. /**
  84140. * Default skybox texture URL.
  84141. */
  84142. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  84143. /**
  84144. * Default environment texture URL.
  84145. */
  84146. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  84147. return EnvironmentHelper;
  84148. }());
  84149. BABYLON.EnvironmentHelper = EnvironmentHelper;
  84150. })(BABYLON || (BABYLON = {}));
  84151. //# sourceMappingURL=babylon.environmentHelper.js.map
  84152. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\ngl_FragColor=color;\n}","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n\n\n\nvec4 finalColor=vec4(finalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*worldPos;\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.y*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive);\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\nvec3 finalColor=colorBase.r*vPrimaryColor.rgb*vPrimaryColor.a;\nfinalColor+=colorBase.g*vSecondaryColor.rgb*vSecondaryColor.a;\nfinalColor+=colorBase.b*vTertiaryColor.rgb*vTertiaryColor.a;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb=dither(vPositionW.xy,color.rgb);\n#endif\ngl_FragColor=color;\n}"};
  84153. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nvec3 dither(vec2 seed,vec3 color) {\nfloat rand=getRand(seed);\ncolor+=mix(-0.5/255.0,0.5/255.0,rand);\ncolor=max(color,0.0);\nreturn color;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\n","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=normalize(vDirectionW);\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else\n#ifdef SHADOWESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else \n#ifdef SHADOWPCF{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","kernelBlurFragment":"#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*KERNEL_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*KERNEL_WEIGHT{X};\n#endif","kernelBlurFragment2":"#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*KERNEL_DEP_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*KERNEL_DEP_WEIGHT{X};\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  84154. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  84155. var BABYLON;
  84156. (function (BABYLON) {
  84157. var GridMaterialDefines = /** @class */ (function (_super) {
  84158. __extends(GridMaterialDefines, _super);
  84159. function GridMaterialDefines() {
  84160. var _this = _super.call(this) || this;
  84161. _this.TRANSPARENT = false;
  84162. _this.FOG = false;
  84163. _this.PREMULTIPLYALPHA = false;
  84164. _this.rebuild();
  84165. return _this;
  84166. }
  84167. return GridMaterialDefines;
  84168. }(BABYLON.MaterialDefines));
  84169. /**
  84170. * The grid materials allows you to wrap any shape with a grid.
  84171. * Colors are customizable.
  84172. */
  84173. var GridMaterial = /** @class */ (function (_super) {
  84174. __extends(GridMaterial, _super);
  84175. /**
  84176. * constructor
  84177. * @param name The name given to the material in order to identify it afterwards.
  84178. * @param scene The scene the material is used in.
  84179. */
  84180. function GridMaterial(name, scene) {
  84181. var _this = _super.call(this, name, scene) || this;
  84182. /**
  84183. * Main color of the grid (e.g. between lines)
  84184. */
  84185. _this.mainColor = BABYLON.Color3.Black();
  84186. /**
  84187. * Color of the grid lines.
  84188. */
  84189. _this.lineColor = BABYLON.Color3.Teal();
  84190. /**
  84191. * The scale of the grid compared to unit.
  84192. */
  84193. _this.gridRatio = 1.0;
  84194. /**
  84195. * Allows setting an offset for the grid lines.
  84196. */
  84197. _this.gridOffset = BABYLON.Vector3.Zero();
  84198. /**
  84199. * The frequency of thicker lines.
  84200. */
  84201. _this.majorUnitFrequency = 10;
  84202. /**
  84203. * The visibility of minor units in the grid.
  84204. */
  84205. _this.minorUnitVisibility = 0.33;
  84206. /**
  84207. * The grid opacity outside of the lines.
  84208. */
  84209. _this.opacity = 1.0;
  84210. /**
  84211. * Determine RBG output is premultiplied by alpha value.
  84212. */
  84213. _this.preMultiplyAlpha = false;
  84214. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  84215. return _this;
  84216. }
  84217. /**
  84218. * Returns wehter or not the grid requires alpha blending.
  84219. */
  84220. GridMaterial.prototype.needAlphaBlending = function () {
  84221. return this.opacity < 1.0;
  84222. };
  84223. GridMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  84224. return this.needAlphaBlending();
  84225. };
  84226. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  84227. if (this.isFrozen) {
  84228. if (this._wasPreviouslyReady && subMesh.effect) {
  84229. return true;
  84230. }
  84231. }
  84232. if (!subMesh._materialDefines) {
  84233. subMesh._materialDefines = new GridMaterialDefines();
  84234. }
  84235. var defines = subMesh._materialDefines;
  84236. var scene = this.getScene();
  84237. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  84238. if (this._renderId === scene.getRenderId()) {
  84239. return true;
  84240. }
  84241. }
  84242. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  84243. defines.TRANSPARENT = !defines.TRANSPARENT;
  84244. defines.markAsUnprocessed();
  84245. }
  84246. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  84247. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  84248. defines.markAsUnprocessed();
  84249. }
  84250. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, false, defines);
  84251. // Get correct effect
  84252. if (defines.isDirty) {
  84253. defines.markAsProcessed();
  84254. scene.resetCachedMaterial();
  84255. // Attributes
  84256. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  84257. // Defines
  84258. var join = defines.toString();
  84259. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "gridOffset", "vFogInfos", "vFogColor", "world", "view"], [], join, undefined, this.onCompiled, this.onError), defines);
  84260. }
  84261. if (!subMesh.effect || !subMesh.effect.isReady()) {
  84262. return false;
  84263. }
  84264. this._renderId = scene.getRenderId();
  84265. this._wasPreviouslyReady = true;
  84266. return true;
  84267. };
  84268. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  84269. var scene = this.getScene();
  84270. var defines = subMesh._materialDefines;
  84271. if (!defines) {
  84272. return;
  84273. }
  84274. var effect = subMesh.effect;
  84275. if (!effect) {
  84276. return;
  84277. }
  84278. this._activeEffect = effect;
  84279. // Matrices
  84280. this.bindOnlyWorldMatrix(world);
  84281. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  84282. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  84283. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  84284. // Uniforms
  84285. if (this._mustRebind(scene, effect)) {
  84286. this._activeEffect.setColor3("mainColor", this.mainColor);
  84287. this._activeEffect.setColor3("lineColor", this.lineColor);
  84288. this._activeEffect.setVector3("gridOffset", this.gridOffset);
  84289. this._gridControl.x = this.gridRatio;
  84290. this._gridControl.y = Math.round(this.majorUnitFrequency);
  84291. this._gridControl.z = this.minorUnitVisibility;
  84292. this._gridControl.w = this.opacity;
  84293. this._activeEffect.setVector4("gridControl", this._gridControl);
  84294. }
  84295. // Fog
  84296. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  84297. this._afterBind(mesh, this._activeEffect);
  84298. };
  84299. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  84300. _super.prototype.dispose.call(this, forceDisposeEffect);
  84301. };
  84302. GridMaterial.prototype.clone = function (name) {
  84303. var _this = this;
  84304. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  84305. };
  84306. GridMaterial.prototype.serialize = function () {
  84307. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  84308. serializationObject.customType = "BABYLON.GridMaterial";
  84309. return serializationObject;
  84310. };
  84311. GridMaterial.prototype.getClassName = function () {
  84312. return "GridMaterial";
  84313. };
  84314. GridMaterial.Parse = function (source, scene, rootUrl) {
  84315. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  84316. };
  84317. __decorate([
  84318. BABYLON.serializeAsColor3()
  84319. ], GridMaterial.prototype, "mainColor", void 0);
  84320. __decorate([
  84321. BABYLON.serializeAsColor3()
  84322. ], GridMaterial.prototype, "lineColor", void 0);
  84323. __decorate([
  84324. BABYLON.serialize()
  84325. ], GridMaterial.prototype, "gridRatio", void 0);
  84326. __decorate([
  84327. BABYLON.serializeAsColor3()
  84328. ], GridMaterial.prototype, "gridOffset", void 0);
  84329. __decorate([
  84330. BABYLON.serialize()
  84331. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  84332. __decorate([
  84333. BABYLON.serialize()
  84334. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  84335. __decorate([
  84336. BABYLON.serialize()
  84337. ], GridMaterial.prototype, "opacity", void 0);
  84338. __decorate([
  84339. BABYLON.serialize()
  84340. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  84341. return GridMaterial;
  84342. }(BABYLON.PushMaterial));
  84343. BABYLON.GridMaterial = GridMaterial;
  84344. })(BABYLON || (BABYLON = {}));
  84345. //# sourceMappingURL=babylon.gridmaterial.js.map
  84346. 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}";
  84347. 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}";
  84348. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  84349. var BABYLON;
  84350. (function (BABYLON) {
  84351. var GLTFLoaderCoordinateSystemMode;
  84352. (function (GLTFLoaderCoordinateSystemMode) {
  84353. /**
  84354. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  84355. */
  84356. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  84357. /**
  84358. * Sets the useRightHandedSystem flag on the scene.
  84359. */
  84360. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  84361. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  84362. var GLTFLoaderAnimationStartMode;
  84363. (function (GLTFLoaderAnimationStartMode) {
  84364. /**
  84365. * No animation will start.
  84366. */
  84367. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  84368. /**
  84369. * The first animation will start.
  84370. */
  84371. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  84372. /**
  84373. * All animations will start.
  84374. */
  84375. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  84376. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  84377. var GLTFFileLoader = /** @class */ (function () {
  84378. function GLTFFileLoader() {
  84379. // #region Common options
  84380. /**
  84381. * Raised when the asset has been parsed.
  84382. * The data.json property stores the glTF JSON.
  84383. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  84384. */
  84385. this.onParsedObservable = new BABYLON.Observable();
  84386. // #endregion
  84387. // #region V2 options
  84388. /**
  84389. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  84390. */
  84391. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  84392. /**
  84393. * The animation start mode (NONE, FIRST, ALL).
  84394. */
  84395. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  84396. /**
  84397. * Set to true to compile materials before raising the success callback.
  84398. */
  84399. this.compileMaterials = false;
  84400. /**
  84401. * Set to true to also compile materials with clip planes.
  84402. */
  84403. this.useClipPlane = false;
  84404. /**
  84405. * Set to true to compile shadow generators before raising the success callback.
  84406. */
  84407. this.compileShadowGenerators = false;
  84408. /**
  84409. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  84410. */
  84411. this.onMeshLoadedObservable = new BABYLON.Observable();
  84412. /**
  84413. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  84414. */
  84415. this.onTextureLoadedObservable = new BABYLON.Observable();
  84416. /**
  84417. * Raised when the loader creates a material after parsing the glTF properties of the material.
  84418. */
  84419. this.onMaterialLoadedObservable = new BABYLON.Observable();
  84420. /**
  84421. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  84422. * For assets with LODs, raised when all of the LODs are complete.
  84423. * For assets without LODs, raised when the model is complete, immediately after onSuccess.
  84424. */
  84425. this.onCompleteObservable = new BABYLON.Observable();
  84426. /**
  84427. * Raised when the loader is disposed.
  84428. */
  84429. this.onDisposeObservable = new BABYLON.Observable();
  84430. // #endregion
  84431. this._loader = null;
  84432. this.name = "gltf";
  84433. this.extensions = {
  84434. ".gltf": { isBinary: false },
  84435. ".glb": { isBinary: true }
  84436. };
  84437. }
  84438. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  84439. set: function (callback) {
  84440. if (this._onParsedObserver) {
  84441. this.onParsedObservable.remove(this._onParsedObserver);
  84442. }
  84443. this._onParsedObserver = this.onParsedObservable.add(callback);
  84444. },
  84445. enumerable: true,
  84446. configurable: true
  84447. });
  84448. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  84449. set: function (callback) {
  84450. if (this._onMeshLoadedObserver) {
  84451. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  84452. }
  84453. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  84454. },
  84455. enumerable: true,
  84456. configurable: true
  84457. });
  84458. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  84459. set: function (callback) {
  84460. if (this._onTextureLoadedObserver) {
  84461. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  84462. }
  84463. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  84464. },
  84465. enumerable: true,
  84466. configurable: true
  84467. });
  84468. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  84469. set: function (callback) {
  84470. if (this._onMaterialLoadedObserver) {
  84471. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  84472. }
  84473. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  84474. },
  84475. enumerable: true,
  84476. configurable: true
  84477. });
  84478. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  84479. set: function (callback) {
  84480. if (this._onCompleteObserver) {
  84481. this.onCompleteObservable.remove(this._onCompleteObserver);
  84482. }
  84483. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  84484. },
  84485. enumerable: true,
  84486. configurable: true
  84487. });
  84488. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  84489. set: function (callback) {
  84490. if (this._onDisposeObserver) {
  84491. this.onDisposeObservable.remove(this._onDisposeObserver);
  84492. }
  84493. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  84494. },
  84495. enumerable: true,
  84496. configurable: true
  84497. });
  84498. /**
  84499. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  84500. */
  84501. GLTFFileLoader.prototype.dispose = function () {
  84502. if (this._loader) {
  84503. this._loader.dispose();
  84504. this._loader = null;
  84505. }
  84506. this.onParsedObservable.clear();
  84507. this.onMeshLoadedObservable.clear();
  84508. this.onTextureLoadedObservable.clear();
  84509. this.onMaterialLoadedObservable.clear();
  84510. this.onCompleteObservable.clear();
  84511. this.onDisposeObservable.notifyObservers(this);
  84512. this.onDisposeObservable.clear();
  84513. };
  84514. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  84515. try {
  84516. var loaderData = this._parse(data);
  84517. this._loader = this._getLoader(loaderData);
  84518. this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  84519. }
  84520. catch (e) {
  84521. if (onError) {
  84522. onError(e.message, e);
  84523. }
  84524. else {
  84525. BABYLON.Tools.Error(e.message);
  84526. }
  84527. }
  84528. };
  84529. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  84530. try {
  84531. var loaderData = this._parse(data);
  84532. this._loader = this._getLoader(loaderData);
  84533. this._loader.loadAsync(scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  84534. }
  84535. catch (e) {
  84536. if (onError) {
  84537. onError(e.message, e);
  84538. }
  84539. else {
  84540. BABYLON.Tools.Error(e.message);
  84541. }
  84542. }
  84543. };
  84544. GLTFFileLoader.prototype.loadAssetsAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  84545. try {
  84546. var loaderData = this._parse(data);
  84547. this._loader = this._getLoader(loaderData);
  84548. this._loader.importMeshAsync(null, scene, loaderData, rootUrl, function (meshes, particleSystems, skeletons) {
  84549. var container = new BABYLON.AssetContainer(scene);
  84550. Array.prototype.push.apply(container.meshes, meshes);
  84551. Array.prototype.push.apply(container.particleSystems, particleSystems);
  84552. Array.prototype.push.apply(container.skeletons, skeletons);
  84553. container.removeAllFromScene();
  84554. onSuccess(container);
  84555. }, onProgress, onError);
  84556. }
  84557. catch (e) {
  84558. if (onError) {
  84559. onError(e.message, e);
  84560. }
  84561. else {
  84562. BABYLON.Tools.Error(e.message);
  84563. }
  84564. }
  84565. };
  84566. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  84567. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  84568. };
  84569. GLTFFileLoader.prototype.createPlugin = function () {
  84570. return new GLTFFileLoader();
  84571. };
  84572. GLTFFileLoader.prototype._parse = function (data) {
  84573. var parsedData;
  84574. if (data instanceof ArrayBuffer) {
  84575. parsedData = GLTFFileLoader._parseBinary(data);
  84576. }
  84577. else {
  84578. parsedData = {
  84579. json: JSON.parse(data),
  84580. bin: null
  84581. };
  84582. }
  84583. this.onParsedObservable.notifyObservers(parsedData);
  84584. return parsedData;
  84585. };
  84586. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  84587. var _this = this;
  84588. var loaderVersion = { major: 2, minor: 0 };
  84589. var asset = loaderData.json.asset || {};
  84590. var version = GLTFFileLoader._parseVersion(asset.version);
  84591. if (!version) {
  84592. throw new Error("Invalid version: " + asset.version);
  84593. }
  84594. if (asset.minVersion !== undefined) {
  84595. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  84596. if (!minVersion) {
  84597. throw new Error("Invalid minimum version: " + asset.minVersion);
  84598. }
  84599. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  84600. throw new Error("Incompatible minimum version: " + asset.minVersion);
  84601. }
  84602. }
  84603. var createLoaders = {
  84604. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  84605. 2: GLTFFileLoader.CreateGLTFLoaderV2
  84606. };
  84607. var createLoader = createLoaders[version.major];
  84608. if (!createLoader) {
  84609. throw new Error("Unsupported version: " + asset.version);
  84610. }
  84611. var loader = createLoader();
  84612. loader.coordinateSystemMode = this.coordinateSystemMode;
  84613. loader.animationStartMode = this.animationStartMode;
  84614. loader.compileMaterials = this.compileMaterials;
  84615. loader.useClipPlane = this.useClipPlane;
  84616. loader.compileShadowGenerators = this.compileShadowGenerators;
  84617. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  84618. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  84619. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  84620. loader.onCompleteObservable.add(function () { return _this.onCompleteObservable.notifyObservers(_this); });
  84621. return loader;
  84622. };
  84623. GLTFFileLoader._parseBinary = function (data) {
  84624. var Binary = {
  84625. Magic: 0x46546C67
  84626. };
  84627. var binaryReader = new BinaryReader(data);
  84628. var magic = binaryReader.readUint32();
  84629. if (magic !== Binary.Magic) {
  84630. throw new Error("Unexpected magic: " + magic);
  84631. }
  84632. var version = binaryReader.readUint32();
  84633. switch (version) {
  84634. case 1: return GLTFFileLoader._parseV1(binaryReader);
  84635. case 2: return GLTFFileLoader._parseV2(binaryReader);
  84636. }
  84637. throw new Error("Unsupported version: " + version);
  84638. };
  84639. GLTFFileLoader._parseV1 = function (binaryReader) {
  84640. var ContentFormat = {
  84641. JSON: 0
  84642. };
  84643. var length = binaryReader.readUint32();
  84644. if (length != binaryReader.getLength()) {
  84645. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  84646. }
  84647. var contentLength = binaryReader.readUint32();
  84648. var contentFormat = binaryReader.readUint32();
  84649. var content;
  84650. switch (contentFormat) {
  84651. case ContentFormat.JSON: {
  84652. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  84653. break;
  84654. }
  84655. default: {
  84656. throw new Error("Unexpected content format: " + contentFormat);
  84657. }
  84658. }
  84659. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  84660. var body = binaryReader.readUint8Array(bytesRemaining);
  84661. return {
  84662. json: content,
  84663. bin: body
  84664. };
  84665. };
  84666. GLTFFileLoader._parseV2 = function (binaryReader) {
  84667. var ChunkFormat = {
  84668. JSON: 0x4E4F534A,
  84669. BIN: 0x004E4942
  84670. };
  84671. var length = binaryReader.readUint32();
  84672. if (length !== binaryReader.getLength()) {
  84673. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  84674. }
  84675. // JSON chunk
  84676. var chunkLength = binaryReader.readUint32();
  84677. var chunkFormat = binaryReader.readUint32();
  84678. if (chunkFormat !== ChunkFormat.JSON) {
  84679. throw new Error("First chunk format is not JSON");
  84680. }
  84681. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  84682. // Look for BIN chunk
  84683. var bin = null;
  84684. while (binaryReader.getPosition() < binaryReader.getLength()) {
  84685. var chunkLength_1 = binaryReader.readUint32();
  84686. var chunkFormat_1 = binaryReader.readUint32();
  84687. switch (chunkFormat_1) {
  84688. case ChunkFormat.JSON: {
  84689. throw new Error("Unexpected JSON chunk");
  84690. }
  84691. case ChunkFormat.BIN: {
  84692. bin = binaryReader.readUint8Array(chunkLength_1);
  84693. break;
  84694. }
  84695. default: {
  84696. // ignore unrecognized chunkFormat
  84697. binaryReader.skipBytes(chunkLength_1);
  84698. break;
  84699. }
  84700. }
  84701. }
  84702. return {
  84703. json: json,
  84704. bin: bin
  84705. };
  84706. };
  84707. GLTFFileLoader._parseVersion = function (version) {
  84708. if (version === "1.0" || version === "1.0.1") {
  84709. return {
  84710. major: 1,
  84711. minor: 0
  84712. };
  84713. }
  84714. var match = (version + "").match(/^(\d+)\.(\d+)/);
  84715. if (!match) {
  84716. return null;
  84717. }
  84718. return {
  84719. major: parseInt(match[1]),
  84720. minor: parseInt(match[2])
  84721. };
  84722. };
  84723. GLTFFileLoader._compareVersion = function (a, b) {
  84724. if (a.major > b.major)
  84725. return 1;
  84726. if (a.major < b.major)
  84727. return -1;
  84728. if (a.minor > b.minor)
  84729. return 1;
  84730. if (a.minor < b.minor)
  84731. return -1;
  84732. return 0;
  84733. };
  84734. GLTFFileLoader._decodeBufferToText = function (buffer) {
  84735. var result = "";
  84736. var length = buffer.byteLength;
  84737. for (var i = 0; i < length; i++) {
  84738. result += String.fromCharCode(buffer[i]);
  84739. }
  84740. return result;
  84741. };
  84742. // #endregion
  84743. // #region V1 options
  84744. GLTFFileLoader.IncrementalLoading = true;
  84745. GLTFFileLoader.HomogeneousCoordinates = false;
  84746. return GLTFFileLoader;
  84747. }());
  84748. BABYLON.GLTFFileLoader = GLTFFileLoader;
  84749. var BinaryReader = /** @class */ (function () {
  84750. function BinaryReader(arrayBuffer) {
  84751. this._arrayBuffer = arrayBuffer;
  84752. this._dataView = new DataView(arrayBuffer);
  84753. this._byteOffset = 0;
  84754. }
  84755. BinaryReader.prototype.getPosition = function () {
  84756. return this._byteOffset;
  84757. };
  84758. BinaryReader.prototype.getLength = function () {
  84759. return this._arrayBuffer.byteLength;
  84760. };
  84761. BinaryReader.prototype.readUint32 = function () {
  84762. var value = this._dataView.getUint32(this._byteOffset, true);
  84763. this._byteOffset += 4;
  84764. return value;
  84765. };
  84766. BinaryReader.prototype.readUint8Array = function (length) {
  84767. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  84768. this._byteOffset += length;
  84769. return value;
  84770. };
  84771. BinaryReader.prototype.skipBytes = function (length) {
  84772. this._byteOffset += length;
  84773. };
  84774. return BinaryReader;
  84775. }());
  84776. if (BABYLON.SceneLoader) {
  84777. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  84778. }
  84779. })(BABYLON || (BABYLON = {}));
  84780. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  84781. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  84782. var BABYLON;
  84783. (function (BABYLON) {
  84784. var GLTF1;
  84785. (function (GLTF1) {
  84786. /**
  84787. * Enums
  84788. */
  84789. var EComponentType;
  84790. (function (EComponentType) {
  84791. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  84792. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  84793. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  84794. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  84795. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  84796. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  84797. var EShaderType;
  84798. (function (EShaderType) {
  84799. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  84800. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  84801. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  84802. var EParameterType;
  84803. (function (EParameterType) {
  84804. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  84805. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  84806. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  84807. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  84808. EParameterType[EParameterType["INT"] = 5124] = "INT";
  84809. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  84810. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  84811. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  84812. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  84813. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  84814. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  84815. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  84816. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  84817. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  84818. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  84819. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  84820. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  84821. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  84822. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  84823. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  84824. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  84825. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  84826. var ETextureWrapMode;
  84827. (function (ETextureWrapMode) {
  84828. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  84829. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  84830. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  84831. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  84832. var ETextureFilterType;
  84833. (function (ETextureFilterType) {
  84834. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  84835. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  84836. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  84837. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  84838. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  84839. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  84840. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  84841. var ETextureFormat;
  84842. (function (ETextureFormat) {
  84843. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  84844. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  84845. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  84846. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  84847. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  84848. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  84849. var ECullingType;
  84850. (function (ECullingType) {
  84851. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  84852. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  84853. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  84854. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  84855. var EBlendingFunction;
  84856. (function (EBlendingFunction) {
  84857. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  84858. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  84859. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  84860. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  84861. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  84862. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  84863. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  84864. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  84865. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  84866. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  84867. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  84868. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  84869. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  84870. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  84871. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  84872. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  84873. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  84874. })(BABYLON || (BABYLON = {}));
  84875. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  84876. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  84877. var BABYLON;
  84878. (function (BABYLON) {
  84879. var GLTF1;
  84880. (function (GLTF1) {
  84881. /**
  84882. * Tokenizer. Used for shaders compatibility
  84883. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  84884. */
  84885. var ETokenType;
  84886. (function (ETokenType) {
  84887. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  84888. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  84889. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  84890. })(ETokenType || (ETokenType = {}));
  84891. var Tokenizer = /** @class */ (function () {
  84892. function Tokenizer(toParse) {
  84893. this._pos = 0;
  84894. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  84895. this._toParse = toParse;
  84896. this._maxPos = toParse.length;
  84897. }
  84898. Tokenizer.prototype.getNextToken = function () {
  84899. if (this.isEnd())
  84900. return ETokenType.END_OF_INPUT;
  84901. this.currentString = this.read();
  84902. this.currentToken = ETokenType.UNKNOWN;
  84903. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  84904. this.currentToken = ETokenType.IDENTIFIER;
  84905. this.currentIdentifier = this.currentString;
  84906. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  84907. this.currentIdentifier += this.currentString;
  84908. this.forward();
  84909. }
  84910. }
  84911. return this.currentToken;
  84912. };
  84913. Tokenizer.prototype.peek = function () {
  84914. return this._toParse[this._pos];
  84915. };
  84916. Tokenizer.prototype.read = function () {
  84917. return this._toParse[this._pos++];
  84918. };
  84919. Tokenizer.prototype.forward = function () {
  84920. this._pos++;
  84921. };
  84922. Tokenizer.prototype.isEnd = function () {
  84923. return this._pos >= this._maxPos;
  84924. };
  84925. return Tokenizer;
  84926. }());
  84927. /**
  84928. * Values
  84929. */
  84930. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  84931. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  84932. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  84933. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  84934. /**
  84935. * Parse
  84936. */
  84937. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  84938. for (var buf in parsedBuffers) {
  84939. var parsedBuffer = parsedBuffers[buf];
  84940. gltfRuntime.buffers[buf] = parsedBuffer;
  84941. gltfRuntime.buffersCount++;
  84942. }
  84943. };
  84944. var parseShaders = function (parsedShaders, gltfRuntime) {
  84945. for (var sha in parsedShaders) {
  84946. var parsedShader = parsedShaders[sha];
  84947. gltfRuntime.shaders[sha] = parsedShader;
  84948. gltfRuntime.shaderscount++;
  84949. }
  84950. };
  84951. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  84952. for (var object in parsedObjects) {
  84953. var parsedObject = parsedObjects[object];
  84954. gltfRuntime[runtimeProperty][object] = parsedObject;
  84955. }
  84956. };
  84957. /**
  84958. * Utils
  84959. */
  84960. var normalizeUVs = function (buffer) {
  84961. if (!buffer) {
  84962. return;
  84963. }
  84964. for (var i = 0; i < buffer.length / 2; i++) {
  84965. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  84966. }
  84967. };
  84968. var getAttribute = function (attributeParameter) {
  84969. if (attributeParameter.semantic === "NORMAL") {
  84970. return "normal";
  84971. }
  84972. else if (attributeParameter.semantic === "POSITION") {
  84973. return "position";
  84974. }
  84975. else if (attributeParameter.semantic === "JOINT") {
  84976. return "matricesIndices";
  84977. }
  84978. else if (attributeParameter.semantic === "WEIGHT") {
  84979. return "matricesWeights";
  84980. }
  84981. else if (attributeParameter.semantic === "COLOR") {
  84982. return "color";
  84983. }
  84984. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  84985. var channel = Number(attributeParameter.semantic.split("_")[1]);
  84986. return "uv" + (channel === 0 ? "" : channel + 1);
  84987. }
  84988. return null;
  84989. };
  84990. /**
  84991. * Loads and creates animations
  84992. */
  84993. var loadAnimations = function (gltfRuntime) {
  84994. for (var anim in gltfRuntime.animations) {
  84995. var animation = gltfRuntime.animations[anim];
  84996. if (!animation.channels || !animation.samplers) {
  84997. continue;
  84998. }
  84999. var lastAnimation = null;
  85000. for (var i = 0; i < animation.channels.length; i++) {
  85001. // Get parameters and load buffers
  85002. var channel = animation.channels[i];
  85003. var sampler = animation.samplers[channel.sampler];
  85004. if (!sampler) {
  85005. continue;
  85006. }
  85007. var inputData = null;
  85008. var outputData = null;
  85009. if (animation.parameters) {
  85010. inputData = animation.parameters[sampler.input];
  85011. outputData = animation.parameters[sampler.output];
  85012. }
  85013. else {
  85014. inputData = sampler.input;
  85015. outputData = sampler.output;
  85016. }
  85017. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  85018. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  85019. var targetID = channel.target.id;
  85020. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  85021. if (targetNode === null) {
  85022. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  85023. }
  85024. if (targetNode === null) {
  85025. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  85026. continue;
  85027. }
  85028. var isBone = targetNode instanceof BABYLON.Bone;
  85029. // Get target path (position, rotation or scaling)
  85030. var targetPath = channel.target.path;
  85031. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  85032. if (targetPathIndex !== -1) {
  85033. targetPath = babylonAnimationPaths[targetPathIndex];
  85034. }
  85035. // Determine animation type
  85036. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  85037. if (!isBone) {
  85038. if (targetPath === "rotationQuaternion") {
  85039. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  85040. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  85041. }
  85042. else {
  85043. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  85044. }
  85045. }
  85046. // Create animation and key frames
  85047. var babylonAnimation = null;
  85048. var keys = [];
  85049. var arrayOffset = 0;
  85050. var modifyKey = false;
  85051. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  85052. babylonAnimation = lastAnimation;
  85053. modifyKey = true;
  85054. }
  85055. if (!modifyKey) {
  85056. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  85057. }
  85058. // For each frame
  85059. for (var j = 0; j < bufferInput.length; j++) {
  85060. var value = null;
  85061. if (targetPath === "rotationQuaternion") {
  85062. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  85063. arrayOffset += 4;
  85064. }
  85065. else {
  85066. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  85067. arrayOffset += 3;
  85068. }
  85069. if (isBone) {
  85070. var bone = targetNode;
  85071. var translation = BABYLON.Vector3.Zero();
  85072. var rotationQuaternion = new BABYLON.Quaternion();
  85073. var scaling = BABYLON.Vector3.Zero();
  85074. // Warning on decompose
  85075. var mat = bone.getBaseMatrix();
  85076. if (modifyKey && lastAnimation) {
  85077. mat = lastAnimation.getKeys()[j].value;
  85078. }
  85079. mat.decompose(scaling, rotationQuaternion, translation);
  85080. if (targetPath === "position") {
  85081. translation = value;
  85082. }
  85083. else if (targetPath === "rotationQuaternion") {
  85084. rotationQuaternion = value;
  85085. }
  85086. else {
  85087. scaling = value;
  85088. }
  85089. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  85090. }
  85091. if (!modifyKey) {
  85092. keys.push({
  85093. frame: bufferInput[j],
  85094. value: value
  85095. });
  85096. }
  85097. else if (lastAnimation) {
  85098. lastAnimation.getKeys()[j].value = value;
  85099. }
  85100. }
  85101. // Finish
  85102. if (!modifyKey && babylonAnimation) {
  85103. babylonAnimation.setKeys(keys);
  85104. targetNode.animations.push(babylonAnimation);
  85105. }
  85106. lastAnimation = babylonAnimation;
  85107. gltfRuntime.scene.stopAnimation(targetNode);
  85108. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  85109. }
  85110. }
  85111. };
  85112. /**
  85113. * Returns the bones transformation matrix
  85114. */
  85115. var configureBoneTransformation = function (node) {
  85116. var mat = null;
  85117. if (node.translation || node.rotation || node.scale) {
  85118. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  85119. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  85120. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  85121. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  85122. }
  85123. else {
  85124. mat = BABYLON.Matrix.FromArray(node.matrix);
  85125. }
  85126. return mat;
  85127. };
  85128. /**
  85129. * Returns the parent bone
  85130. */
  85131. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  85132. // Try to find
  85133. for (var i = 0; i < newSkeleton.bones.length; i++) {
  85134. if (newSkeleton.bones[i].name === jointName) {
  85135. return newSkeleton.bones[i];
  85136. }
  85137. }
  85138. // Not found, search in gltf nodes
  85139. var nodes = gltfRuntime.nodes;
  85140. for (var nde in nodes) {
  85141. var node = nodes[nde];
  85142. if (!node.jointName) {
  85143. continue;
  85144. }
  85145. var children = node.children;
  85146. for (var i = 0; i < children.length; i++) {
  85147. var child = gltfRuntime.nodes[children[i]];
  85148. if (!child.jointName) {
  85149. continue;
  85150. }
  85151. if (child.jointName === jointName) {
  85152. var mat = configureBoneTransformation(node);
  85153. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  85154. bone.id = nde;
  85155. return bone;
  85156. }
  85157. }
  85158. }
  85159. return null;
  85160. };
  85161. /**
  85162. * Returns the appropriate root node
  85163. */
  85164. var getNodeToRoot = function (nodesToRoot, id) {
  85165. for (var i = 0; i < nodesToRoot.length; i++) {
  85166. var nodeToRoot = nodesToRoot[i];
  85167. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  85168. var child = nodeToRoot.node.children[j];
  85169. if (child === id) {
  85170. return nodeToRoot.bone;
  85171. }
  85172. }
  85173. }
  85174. return null;
  85175. };
  85176. /**
  85177. * Returns the node with the joint name
  85178. */
  85179. var getJointNode = function (gltfRuntime, jointName) {
  85180. var nodes = gltfRuntime.nodes;
  85181. var node = nodes[jointName];
  85182. if (node) {
  85183. return {
  85184. node: node,
  85185. id: jointName
  85186. };
  85187. }
  85188. for (var nde in nodes) {
  85189. node = nodes[nde];
  85190. if (node.jointName === jointName) {
  85191. return {
  85192. node: node,
  85193. id: nde
  85194. };
  85195. }
  85196. }
  85197. return null;
  85198. };
  85199. /**
  85200. * Checks if a nodes is in joints
  85201. */
  85202. var nodeIsInJoints = function (skins, id) {
  85203. for (var i = 0; i < skins.jointNames.length; i++) {
  85204. if (skins.jointNames[i] === id) {
  85205. return true;
  85206. }
  85207. }
  85208. return false;
  85209. };
  85210. /**
  85211. * Fills the nodes to root for bones and builds hierarchy
  85212. */
  85213. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  85214. // Creates nodes for root
  85215. for (var nde in gltfRuntime.nodes) {
  85216. var node = gltfRuntime.nodes[nde];
  85217. var id = nde;
  85218. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  85219. continue;
  85220. }
  85221. // Create node to root bone
  85222. var mat = configureBoneTransformation(node);
  85223. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  85224. bone.id = id;
  85225. nodesToRoot.push({ bone: bone, node: node, id: id });
  85226. }
  85227. // Parenting
  85228. for (var i = 0; i < nodesToRoot.length; i++) {
  85229. var nodeToRoot = nodesToRoot[i];
  85230. var children = nodeToRoot.node.children;
  85231. for (var j = 0; j < children.length; j++) {
  85232. var child = null;
  85233. for (var k = 0; k < nodesToRoot.length; k++) {
  85234. if (nodesToRoot[k].id === children[j]) {
  85235. child = nodesToRoot[k];
  85236. break;
  85237. }
  85238. }
  85239. if (child) {
  85240. child.bone._parent = nodeToRoot.bone;
  85241. nodeToRoot.bone.children.push(child.bone);
  85242. }
  85243. }
  85244. }
  85245. };
  85246. /**
  85247. * Imports a skeleton
  85248. */
  85249. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  85250. if (!newSkeleton) {
  85251. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  85252. }
  85253. if (!skins.babylonSkeleton) {
  85254. return newSkeleton;
  85255. }
  85256. // Find the root bones
  85257. var nodesToRoot = [];
  85258. var nodesToRootToAdd = [];
  85259. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  85260. newSkeleton.bones = [];
  85261. // Joints
  85262. for (var i = 0; i < skins.jointNames.length; i++) {
  85263. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  85264. if (!jointNode) {
  85265. continue;
  85266. }
  85267. var node = jointNode.node;
  85268. if (!node) {
  85269. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  85270. continue;
  85271. }
  85272. var id = jointNode.id;
  85273. // Optimize, if the bone already exists...
  85274. var existingBone = gltfRuntime.scene.getBoneByID(id);
  85275. if (existingBone) {
  85276. newSkeleton.bones.push(existingBone);
  85277. continue;
  85278. }
  85279. // Search for parent bone
  85280. var foundBone = false;
  85281. var parentBone = null;
  85282. for (var j = 0; j < i; j++) {
  85283. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  85284. if (!jointNode_1) {
  85285. continue;
  85286. }
  85287. var joint = jointNode_1.node;
  85288. if (!joint) {
  85289. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  85290. continue;
  85291. }
  85292. var children = joint.children;
  85293. if (!children) {
  85294. continue;
  85295. }
  85296. foundBone = false;
  85297. for (var k = 0; k < children.length; k++) {
  85298. if (children[k] === id) {
  85299. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  85300. foundBone = true;
  85301. break;
  85302. }
  85303. }
  85304. if (foundBone) {
  85305. break;
  85306. }
  85307. }
  85308. // Create bone
  85309. var mat = configureBoneTransformation(node);
  85310. if (!parentBone && nodesToRoot.length > 0) {
  85311. parentBone = getNodeToRoot(nodesToRoot, id);
  85312. if (parentBone) {
  85313. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  85314. nodesToRootToAdd.push(parentBone);
  85315. }
  85316. }
  85317. }
  85318. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  85319. bone.id = id;
  85320. }
  85321. // Polish
  85322. var bones = newSkeleton.bones;
  85323. newSkeleton.bones = [];
  85324. for (var i = 0; i < skins.jointNames.length; i++) {
  85325. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  85326. if (!jointNode) {
  85327. continue;
  85328. }
  85329. for (var j = 0; j < bones.length; j++) {
  85330. if (bones[j].id === jointNode.id) {
  85331. newSkeleton.bones.push(bones[j]);
  85332. break;
  85333. }
  85334. }
  85335. }
  85336. newSkeleton.prepare();
  85337. // Finish
  85338. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  85339. newSkeleton.bones.push(nodesToRootToAdd[i]);
  85340. }
  85341. return newSkeleton;
  85342. };
  85343. /**
  85344. * Imports a mesh and its geometries
  85345. */
  85346. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  85347. if (!newMesh) {
  85348. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  85349. newMesh.id = id;
  85350. }
  85351. if (!node.babylonNode) {
  85352. return newMesh;
  85353. }
  85354. var subMaterials = [];
  85355. var vertexData = new BABYLON.VertexData();
  85356. var geometry = new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  85357. var verticesStarts = new Array();
  85358. var verticesCounts = new Array();
  85359. var indexStarts = new Array();
  85360. var indexCounts = new Array();
  85361. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  85362. var meshID = meshes[meshIndex];
  85363. var mesh = gltfRuntime.meshes[meshID];
  85364. if (!mesh) {
  85365. continue;
  85366. }
  85367. // Positions, normals and UVs
  85368. for (var i = 0; i < mesh.primitives.length; i++) {
  85369. // Temporary vertex data
  85370. var tempVertexData = new BABYLON.VertexData();
  85371. var primitive = mesh.primitives[i];
  85372. if (primitive.mode !== 4) {
  85373. // continue;
  85374. }
  85375. var attributes = primitive.attributes;
  85376. var accessor = null;
  85377. var buffer = null;
  85378. // Set positions, normal and uvs
  85379. for (var semantic in attributes) {
  85380. // Link accessor and buffer view
  85381. accessor = gltfRuntime.accessors[attributes[semantic]];
  85382. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  85383. if (semantic === "NORMAL") {
  85384. tempVertexData.normals = new Float32Array(buffer.length);
  85385. tempVertexData.normals.set(buffer);
  85386. }
  85387. else if (semantic === "POSITION") {
  85388. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  85389. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  85390. for (var j = 0; j < buffer.length; j += 4) {
  85391. tempVertexData.positions[j] = buffer[j];
  85392. tempVertexData.positions[j + 1] = buffer[j + 1];
  85393. tempVertexData.positions[j + 2] = buffer[j + 2];
  85394. }
  85395. }
  85396. else {
  85397. tempVertexData.positions = new Float32Array(buffer.length);
  85398. tempVertexData.positions.set(buffer);
  85399. }
  85400. verticesCounts.push(tempVertexData.positions.length);
  85401. }
  85402. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  85403. var channel = Number(semantic.split("_")[1]);
  85404. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  85405. var uvs = new Float32Array(buffer.length);
  85406. uvs.set(buffer);
  85407. normalizeUVs(uvs);
  85408. tempVertexData.set(uvs, uvKind);
  85409. }
  85410. else if (semantic === "JOINT") {
  85411. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  85412. tempVertexData.matricesIndices.set(buffer);
  85413. }
  85414. else if (semantic === "WEIGHT") {
  85415. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  85416. tempVertexData.matricesWeights.set(buffer);
  85417. }
  85418. else if (semantic === "COLOR") {
  85419. tempVertexData.colors = new Float32Array(buffer.length);
  85420. tempVertexData.colors.set(buffer);
  85421. }
  85422. }
  85423. // Indices
  85424. accessor = gltfRuntime.accessors[primitive.indices];
  85425. if (accessor) {
  85426. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  85427. tempVertexData.indices = new Int32Array(buffer.length);
  85428. tempVertexData.indices.set(buffer);
  85429. indexCounts.push(tempVertexData.indices.length);
  85430. }
  85431. else {
  85432. // Set indices on the fly
  85433. var indices = [];
  85434. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  85435. indices.push(j);
  85436. }
  85437. tempVertexData.indices = new Int32Array(indices);
  85438. indexCounts.push(tempVertexData.indices.length);
  85439. }
  85440. vertexData.merge(tempVertexData);
  85441. // Sub material
  85442. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  85443. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  85444. // Update vertices start and index start
  85445. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  85446. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  85447. }
  85448. }
  85449. var material;
  85450. if (subMaterials.length > 1) {
  85451. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  85452. material.subMaterials = subMaterials;
  85453. }
  85454. else {
  85455. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  85456. }
  85457. if (subMaterials.length === 1) {
  85458. material = subMaterials[0];
  85459. }
  85460. if (!newMesh.material) {
  85461. newMesh.material = material;
  85462. }
  85463. // Apply geometry
  85464. geometry.setAllVerticesData(vertexData, false);
  85465. newMesh.computeWorldMatrix(true);
  85466. // Apply submeshes
  85467. newMesh.subMeshes = [];
  85468. var index = 0;
  85469. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  85470. var meshID = meshes[meshIndex];
  85471. var mesh = gltfRuntime.meshes[meshID];
  85472. if (!mesh) {
  85473. continue;
  85474. }
  85475. for (var i = 0; i < mesh.primitives.length; i++) {
  85476. if (mesh.primitives[i].mode !== 4) {
  85477. //continue;
  85478. }
  85479. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  85480. index++;
  85481. }
  85482. }
  85483. // Finish
  85484. return newMesh;
  85485. };
  85486. /**
  85487. * Configure node transformation from position, rotation and scaling
  85488. */
  85489. var configureNode = function (newNode, position, rotation, scaling) {
  85490. if (newNode.position) {
  85491. newNode.position = position;
  85492. }
  85493. if (newNode.rotationQuaternion || newNode.rotation) {
  85494. newNode.rotationQuaternion = rotation;
  85495. }
  85496. if (newNode.scaling) {
  85497. newNode.scaling = scaling;
  85498. }
  85499. };
  85500. /**
  85501. * Configures node from transformation matrix
  85502. */
  85503. var configureNodeFromMatrix = function (newNode, node, parent) {
  85504. if (node.matrix) {
  85505. var position = new BABYLON.Vector3(0, 0, 0);
  85506. var rotation = new BABYLON.Quaternion();
  85507. var scaling = new BABYLON.Vector3(0, 0, 0);
  85508. var mat = BABYLON.Matrix.FromArray(node.matrix);
  85509. mat.decompose(scaling, rotation, position);
  85510. configureNode(newNode, position, rotation, scaling);
  85511. }
  85512. else if (node.translation && node.rotation && node.scale) {
  85513. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  85514. }
  85515. newNode.computeWorldMatrix(true);
  85516. };
  85517. /**
  85518. * Imports a node
  85519. */
  85520. var importNode = function (gltfRuntime, node, id, parent) {
  85521. var lastNode = null;
  85522. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  85523. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  85524. return null;
  85525. }
  85526. }
  85527. // Meshes
  85528. if (node.skin) {
  85529. if (node.meshes) {
  85530. var skin = gltfRuntime.skins[node.skin];
  85531. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  85532. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  85533. if (newMesh.skeleton === null) {
  85534. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  85535. if (!skin.babylonSkeleton) {
  85536. skin.babylonSkeleton = newMesh.skeleton;
  85537. }
  85538. }
  85539. lastNode = newMesh;
  85540. }
  85541. }
  85542. else if (node.meshes) {
  85543. /**
  85544. * Improve meshes property
  85545. */
  85546. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  85547. lastNode = newMesh;
  85548. }
  85549. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  85550. var light = gltfRuntime.lights[node.light];
  85551. if (light) {
  85552. if (light.type === "ambient") {
  85553. var ambienLight = light[light.type];
  85554. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  85555. hemiLight.name = node.name || "";
  85556. if (ambienLight.color) {
  85557. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  85558. }
  85559. lastNode = hemiLight;
  85560. }
  85561. else if (light.type === "directional") {
  85562. var directionalLight = light[light.type];
  85563. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  85564. dirLight.name = node.name || "";
  85565. if (directionalLight.color) {
  85566. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  85567. }
  85568. lastNode = dirLight;
  85569. }
  85570. else if (light.type === "point") {
  85571. var pointLight = light[light.type];
  85572. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  85573. ptLight.name = node.name || "";
  85574. if (pointLight.color) {
  85575. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  85576. }
  85577. lastNode = ptLight;
  85578. }
  85579. else if (light.type === "spot") {
  85580. var spotLight = light[light.type];
  85581. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  85582. spLight.name = node.name || "";
  85583. if (spotLight.color) {
  85584. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  85585. }
  85586. if (spotLight.fallOfAngle) {
  85587. spLight.angle = spotLight.fallOfAngle;
  85588. }
  85589. if (spotLight.fallOffExponent) {
  85590. spLight.exponent = spotLight.fallOffExponent;
  85591. }
  85592. lastNode = spLight;
  85593. }
  85594. }
  85595. }
  85596. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  85597. var camera = gltfRuntime.cameras[node.camera];
  85598. if (camera) {
  85599. if (camera.type === "orthographic") {
  85600. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  85601. orthoCamera.name = node.name || "";
  85602. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  85603. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  85604. lastNode = orthoCamera;
  85605. }
  85606. else if (camera.type === "perspective") {
  85607. var perspectiveCamera = camera[camera.type];
  85608. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  85609. persCamera.name = node.name || "";
  85610. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  85611. if (!perspectiveCamera.aspectRatio) {
  85612. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  85613. }
  85614. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  85615. persCamera.maxZ = perspectiveCamera.zfar;
  85616. persCamera.minZ = perspectiveCamera.znear;
  85617. }
  85618. lastNode = persCamera;
  85619. }
  85620. }
  85621. }
  85622. // Empty node
  85623. if (!node.jointName) {
  85624. if (node.babylonNode) {
  85625. return node.babylonNode;
  85626. }
  85627. else if (lastNode === null) {
  85628. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  85629. node.babylonNode = dummy;
  85630. lastNode = dummy;
  85631. }
  85632. }
  85633. if (lastNode !== null) {
  85634. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  85635. configureNodeFromMatrix(lastNode, node, parent);
  85636. }
  85637. else {
  85638. var translation = node.translation || [0, 0, 0];
  85639. var rotation = node.rotation || [0, 0, 0, 1];
  85640. var scale = node.scale || [1, 1, 1];
  85641. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  85642. }
  85643. lastNode.updateCache(true);
  85644. node.babylonNode = lastNode;
  85645. }
  85646. return lastNode;
  85647. };
  85648. /**
  85649. * Traverses nodes and creates them
  85650. */
  85651. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  85652. if (meshIncluded === void 0) { meshIncluded = false; }
  85653. var node = gltfRuntime.nodes[id];
  85654. var newNode = null;
  85655. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  85656. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  85657. meshIncluded = true;
  85658. }
  85659. else {
  85660. meshIncluded = false;
  85661. }
  85662. }
  85663. else {
  85664. meshIncluded = true;
  85665. }
  85666. if (!node.jointName && meshIncluded) {
  85667. newNode = importNode(gltfRuntime, node, id, parent);
  85668. if (newNode !== null) {
  85669. newNode.id = id;
  85670. newNode.parent = parent;
  85671. }
  85672. }
  85673. if (node.children) {
  85674. for (var i = 0; i < node.children.length; i++) {
  85675. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  85676. }
  85677. }
  85678. };
  85679. /**
  85680. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  85681. */
  85682. var postLoad = function (gltfRuntime) {
  85683. // Nodes
  85684. var currentScene = gltfRuntime.currentScene;
  85685. if (currentScene) {
  85686. for (var i = 0; i < currentScene.nodes.length; i++) {
  85687. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  85688. }
  85689. }
  85690. else {
  85691. for (var thing in gltfRuntime.scenes) {
  85692. currentScene = gltfRuntime.scenes[thing];
  85693. for (var i = 0; i < currentScene.nodes.length; i++) {
  85694. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  85695. }
  85696. }
  85697. }
  85698. // Set animations
  85699. loadAnimations(gltfRuntime);
  85700. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  85701. var skeleton = gltfRuntime.scene.skeletons[i];
  85702. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  85703. }
  85704. };
  85705. /**
  85706. * onBind shaderrs callback to set uniforms and matrices
  85707. */
  85708. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  85709. var materialValues = material.values || technique.parameters;
  85710. for (var unif in unTreatedUniforms) {
  85711. var uniform = unTreatedUniforms[unif];
  85712. var type = uniform.type;
  85713. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  85714. if (uniform.semantic && !uniform.source && !uniform.node) {
  85715. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  85716. }
  85717. else if (uniform.semantic && (uniform.source || uniform.node)) {
  85718. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  85719. if (source === null) {
  85720. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  85721. }
  85722. if (source === null) {
  85723. continue;
  85724. }
  85725. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  85726. }
  85727. }
  85728. else {
  85729. var value = materialValues[technique.uniforms[unif]];
  85730. if (!value) {
  85731. continue;
  85732. }
  85733. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  85734. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  85735. if (texture === null || texture === undefined) {
  85736. continue;
  85737. }
  85738. shaderMaterial.getEffect().setTexture(unif, texture);
  85739. }
  85740. else {
  85741. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  85742. }
  85743. }
  85744. }
  85745. onSuccess(shaderMaterial);
  85746. };
  85747. /**
  85748. * Prepare uniforms to send the only one time
  85749. * Loads the appropriate textures
  85750. */
  85751. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  85752. var materialValues = material.values || technique.parameters;
  85753. var techniqueUniforms = technique.uniforms;
  85754. /**
  85755. * Prepare values here (not matrices)
  85756. */
  85757. for (var unif in unTreatedUniforms) {
  85758. var uniform = unTreatedUniforms[unif];
  85759. var type = uniform.type;
  85760. var value = materialValues[techniqueUniforms[unif]];
  85761. if (value === undefined) {
  85762. // In case the value is the same for all materials
  85763. value = uniform.value;
  85764. }
  85765. if (!value) {
  85766. continue;
  85767. }
  85768. var onLoadTexture = function (uniformName) {
  85769. return function (texture) {
  85770. if (uniform.value && uniformName) {
  85771. // Static uniform
  85772. shaderMaterial.setTexture(uniformName, texture);
  85773. delete unTreatedUniforms[uniformName];
  85774. }
  85775. };
  85776. };
  85777. // Texture (sampler2D)
  85778. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  85779. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  85780. }
  85781. else {
  85782. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  85783. // Static uniform
  85784. delete unTreatedUniforms[unif];
  85785. }
  85786. }
  85787. }
  85788. };
  85789. /**
  85790. * Shader compilation failed
  85791. */
  85792. var onShaderCompileError = function (program, shaderMaterial, onError) {
  85793. return function (effect, error) {
  85794. shaderMaterial.dispose(true);
  85795. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  85796. };
  85797. };
  85798. /**
  85799. * Shader compilation success
  85800. */
  85801. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  85802. return function (_) {
  85803. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  85804. shaderMaterial.onBind = function (mesh) {
  85805. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  85806. };
  85807. };
  85808. };
  85809. /**
  85810. * Returns the appropriate uniform if already handled by babylon
  85811. */
  85812. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  85813. for (var unif in technique.uniforms) {
  85814. var uniform = technique.uniforms[unif];
  85815. var uniformParameter = technique.parameters[uniform];
  85816. if (tokenizer.currentIdentifier === unif) {
  85817. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  85818. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  85819. if (transformIndex !== -1) {
  85820. delete unTreatedUniforms[unif];
  85821. return babylonTransforms[transformIndex];
  85822. }
  85823. }
  85824. }
  85825. }
  85826. return tokenizer.currentIdentifier;
  85827. };
  85828. /**
  85829. * All shaders loaded. Create materials one by one
  85830. */
  85831. var importMaterials = function (gltfRuntime) {
  85832. // Create materials
  85833. for (var mat in gltfRuntime.materials) {
  85834. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  85835. }
  85836. };
  85837. /**
  85838. * Implementation of the base glTF spec
  85839. */
  85840. var GLTFLoaderBase = /** @class */ (function () {
  85841. function GLTFLoaderBase() {
  85842. }
  85843. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  85844. var gltfRuntime = {
  85845. extensions: {},
  85846. accessors: {},
  85847. buffers: {},
  85848. bufferViews: {},
  85849. meshes: {},
  85850. lights: {},
  85851. cameras: {},
  85852. nodes: {},
  85853. images: {},
  85854. textures: {},
  85855. shaders: {},
  85856. programs: {},
  85857. samplers: {},
  85858. techniques: {},
  85859. materials: {},
  85860. animations: {},
  85861. skins: {},
  85862. extensionsUsed: [],
  85863. scenes: {},
  85864. buffersCount: 0,
  85865. shaderscount: 0,
  85866. scene: scene,
  85867. rootUrl: rootUrl,
  85868. loadedBufferCount: 0,
  85869. loadedBufferViews: {},
  85870. loadedShaderCount: 0,
  85871. importOnlyMeshes: false,
  85872. dummyNodes: []
  85873. };
  85874. // Parse
  85875. if (parsedData.extensions) {
  85876. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  85877. }
  85878. if (parsedData.extensionsUsed) {
  85879. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  85880. }
  85881. if (parsedData.buffers) {
  85882. parseBuffers(parsedData.buffers, gltfRuntime);
  85883. }
  85884. if (parsedData.bufferViews) {
  85885. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  85886. }
  85887. if (parsedData.accessors) {
  85888. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  85889. }
  85890. if (parsedData.meshes) {
  85891. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  85892. }
  85893. if (parsedData.lights) {
  85894. parseObject(parsedData.lights, "lights", gltfRuntime);
  85895. }
  85896. if (parsedData.cameras) {
  85897. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  85898. }
  85899. if (parsedData.nodes) {
  85900. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  85901. }
  85902. if (parsedData.images) {
  85903. parseObject(parsedData.images, "images", gltfRuntime);
  85904. }
  85905. if (parsedData.textures) {
  85906. parseObject(parsedData.textures, "textures", gltfRuntime);
  85907. }
  85908. if (parsedData.shaders) {
  85909. parseShaders(parsedData.shaders, gltfRuntime);
  85910. }
  85911. if (parsedData.programs) {
  85912. parseObject(parsedData.programs, "programs", gltfRuntime);
  85913. }
  85914. if (parsedData.samplers) {
  85915. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  85916. }
  85917. if (parsedData.techniques) {
  85918. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  85919. }
  85920. if (parsedData.materials) {
  85921. parseObject(parsedData.materials, "materials", gltfRuntime);
  85922. }
  85923. if (parsedData.animations) {
  85924. parseObject(parsedData.animations, "animations", gltfRuntime);
  85925. }
  85926. if (parsedData.skins) {
  85927. parseObject(parsedData.skins, "skins", gltfRuntime);
  85928. }
  85929. if (parsedData.scenes) {
  85930. gltfRuntime.scenes = parsedData.scenes;
  85931. }
  85932. if (parsedData.scene && parsedData.scenes) {
  85933. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  85934. }
  85935. return gltfRuntime;
  85936. };
  85937. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  85938. var buffer = gltfRuntime.buffers[id];
  85939. if (GLTF1.GLTFUtils.IsBase64(buffer.uri)) {
  85940. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(buffer.uri))); });
  85941. }
  85942. else {
  85943. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  85944. if (request) {
  85945. onError(request.status + " " + request.statusText);
  85946. }
  85947. });
  85948. }
  85949. };
  85950. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  85951. var texture = gltfRuntime.textures[id];
  85952. if (!texture || !texture.source) {
  85953. onError("");
  85954. return;
  85955. }
  85956. if (texture.babylonTexture) {
  85957. onSuccess(null);
  85958. return;
  85959. }
  85960. var source = gltfRuntime.images[texture.source];
  85961. if (GLTF1.GLTFUtils.IsBase64(source.uri)) {
  85962. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(source.uri))); });
  85963. }
  85964. else {
  85965. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  85966. if (request) {
  85967. onError(request.status + " " + request.statusText);
  85968. }
  85969. });
  85970. }
  85971. };
  85972. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  85973. var texture = gltfRuntime.textures[id];
  85974. if (texture.babylonTexture) {
  85975. onSuccess(texture.babylonTexture);
  85976. return;
  85977. }
  85978. var sampler = gltfRuntime.samplers[texture.sampler];
  85979. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  85980. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  85981. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  85982. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  85983. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  85984. var blob = new Blob([buffer]);
  85985. var blobURL = URL.createObjectURL(blob);
  85986. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  85987. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  85988. if (sampler.wrapS !== undefined) {
  85989. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  85990. }
  85991. if (sampler.wrapT !== undefined) {
  85992. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  85993. }
  85994. newTexture.name = id;
  85995. texture.babylonTexture = newTexture;
  85996. onSuccess(newTexture);
  85997. };
  85998. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  85999. var shader = gltfRuntime.shaders[id];
  86000. if (GLTF1.GLTFUtils.IsBase64(shader.uri)) {
  86001. var shaderString = atob(shader.uri.split(",")[1]);
  86002. onSuccess(shaderString);
  86003. }
  86004. else {
  86005. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  86006. if (request) {
  86007. onError(request.status + " " + request.statusText);
  86008. }
  86009. });
  86010. }
  86011. };
  86012. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  86013. var material = gltfRuntime.materials[id];
  86014. if (!material.technique) {
  86015. if (onError) {
  86016. onError("No technique found.");
  86017. }
  86018. return;
  86019. }
  86020. var technique = gltfRuntime.techniques[material.technique];
  86021. if (!technique) {
  86022. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  86023. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  86024. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  86025. onSuccess(defaultMaterial);
  86026. return;
  86027. }
  86028. var program = gltfRuntime.programs[technique.program];
  86029. var states = technique.states;
  86030. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  86031. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  86032. var newVertexShader = "";
  86033. var newPixelShader = "";
  86034. var vertexTokenizer = new Tokenizer(vertexShader);
  86035. var pixelTokenizer = new Tokenizer(pixelShader);
  86036. var unTreatedUniforms = {};
  86037. var uniforms = [];
  86038. var attributes = [];
  86039. var samplers = [];
  86040. // Fill uniform, sampler2D and attributes
  86041. for (var unif in technique.uniforms) {
  86042. var uniform = technique.uniforms[unif];
  86043. var uniformParameter = technique.parameters[uniform];
  86044. unTreatedUniforms[unif] = uniformParameter;
  86045. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  86046. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  86047. if (transformIndex !== -1) {
  86048. uniforms.push(babylonTransforms[transformIndex]);
  86049. delete unTreatedUniforms[unif];
  86050. }
  86051. else {
  86052. uniforms.push(unif);
  86053. }
  86054. }
  86055. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  86056. samplers.push(unif);
  86057. }
  86058. else {
  86059. uniforms.push(unif);
  86060. }
  86061. }
  86062. for (var attr in technique.attributes) {
  86063. var attribute = technique.attributes[attr];
  86064. var attributeParameter = technique.parameters[attribute];
  86065. if (attributeParameter.semantic) {
  86066. attributes.push(getAttribute(attributeParameter));
  86067. }
  86068. }
  86069. // Configure vertex shader
  86070. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  86071. var tokenType = vertexTokenizer.currentToken;
  86072. if (tokenType !== ETokenType.IDENTIFIER) {
  86073. newVertexShader += vertexTokenizer.currentString;
  86074. continue;
  86075. }
  86076. var foundAttribute = false;
  86077. for (var attr in technique.attributes) {
  86078. var attribute = technique.attributes[attr];
  86079. var attributeParameter = technique.parameters[attribute];
  86080. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  86081. newVertexShader += getAttribute(attributeParameter);
  86082. foundAttribute = true;
  86083. break;
  86084. }
  86085. }
  86086. if (foundAttribute) {
  86087. continue;
  86088. }
  86089. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  86090. }
  86091. // Configure pixel shader
  86092. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  86093. var tokenType = pixelTokenizer.currentToken;
  86094. if (tokenType !== ETokenType.IDENTIFIER) {
  86095. newPixelShader += pixelTokenizer.currentString;
  86096. continue;
  86097. }
  86098. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  86099. }
  86100. // Create shader material
  86101. var shaderPath = {
  86102. vertex: program.vertexShader + id,
  86103. fragment: program.fragmentShader + id
  86104. };
  86105. var options = {
  86106. attributes: attributes,
  86107. uniforms: uniforms,
  86108. samplers: samplers,
  86109. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  86110. };
  86111. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  86112. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  86113. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  86114. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  86115. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  86116. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  86117. if (states && states.functions) {
  86118. var functions = states.functions;
  86119. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  86120. shaderMaterial.backFaceCulling = false;
  86121. }
  86122. var blendFunc = functions.blendFuncSeparate;
  86123. if (blendFunc) {
  86124. 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) {
  86125. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  86126. }
  86127. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  86128. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  86129. }
  86130. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  86131. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  86132. }
  86133. 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) {
  86134. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  86135. }
  86136. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  86137. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  86138. }
  86139. 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) {
  86140. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  86141. }
  86142. }
  86143. }
  86144. };
  86145. return GLTFLoaderBase;
  86146. }());
  86147. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  86148. /**
  86149. * glTF V1 Loader
  86150. */
  86151. var GLTFLoader = /** @class */ (function () {
  86152. function GLTFLoader() {
  86153. // #region Stubs for IGLTFLoader interface
  86154. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  86155. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  86156. this.compileMaterials = false;
  86157. this.useClipPlane = false;
  86158. this.compileShadowGenerators = false;
  86159. this.onDisposeObservable = new BABYLON.Observable();
  86160. this.onMeshLoadedObservable = new BABYLON.Observable();
  86161. this.onTextureLoadedObservable = new BABYLON.Observable();
  86162. this.onMaterialLoadedObservable = new BABYLON.Observable();
  86163. this.onCompleteObservable = new BABYLON.Observable();
  86164. }
  86165. GLTFLoader.RegisterExtension = function (extension) {
  86166. if (GLTFLoader.Extensions[extension.name]) {
  86167. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  86168. return;
  86169. }
  86170. GLTFLoader.Extensions[extension.name] = extension;
  86171. };
  86172. GLTFLoader.prototype.dispose = function () { };
  86173. // #endregion
  86174. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  86175. var _this = this;
  86176. scene.useRightHandedSystem = true;
  86177. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  86178. gltfRuntime.importOnlyMeshes = true;
  86179. if (meshesNames === "") {
  86180. gltfRuntime.importMeshesNames = [];
  86181. }
  86182. else if (typeof meshesNames === "string") {
  86183. gltfRuntime.importMeshesNames = [meshesNames];
  86184. }
  86185. else if (meshesNames && !(meshesNames instanceof Array)) {
  86186. gltfRuntime.importMeshesNames = [meshesNames];
  86187. }
  86188. else {
  86189. gltfRuntime.importMeshesNames = [];
  86190. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  86191. }
  86192. // Create nodes
  86193. _this._createNodes(gltfRuntime);
  86194. var meshes = new Array();
  86195. var skeletons = new Array();
  86196. // Fill arrays of meshes and skeletons
  86197. for (var nde in gltfRuntime.nodes) {
  86198. var node = gltfRuntime.nodes[nde];
  86199. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  86200. meshes.push(node.babylonNode);
  86201. }
  86202. }
  86203. for (var skl in gltfRuntime.skins) {
  86204. var skin = gltfRuntime.skins[skl];
  86205. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  86206. skeletons.push(skin.babylonSkeleton);
  86207. }
  86208. }
  86209. // Load buffers, shaders, materials, etc.
  86210. _this._loadBuffersAsync(gltfRuntime, function () {
  86211. _this._loadShadersAsync(gltfRuntime, function () {
  86212. importMaterials(gltfRuntime);
  86213. postLoad(gltfRuntime);
  86214. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  86215. onSuccess(meshes, [], skeletons);
  86216. }
  86217. });
  86218. }, onProgress);
  86219. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  86220. onSuccess(meshes, [], skeletons);
  86221. }
  86222. }, onError);
  86223. return true;
  86224. };
  86225. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  86226. var _this = this;
  86227. scene.useRightHandedSystem = true;
  86228. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  86229. // Load runtime extensios
  86230. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  86231. // Create nodes
  86232. _this._createNodes(gltfRuntime);
  86233. // Load buffers, shaders, materials, etc.
  86234. _this._loadBuffersAsync(gltfRuntime, function () {
  86235. _this._loadShadersAsync(gltfRuntime, function () {
  86236. importMaterials(gltfRuntime);
  86237. postLoad(gltfRuntime);
  86238. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  86239. onSuccess();
  86240. }
  86241. });
  86242. });
  86243. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  86244. onSuccess();
  86245. }
  86246. }, onError);
  86247. }, onError);
  86248. };
  86249. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  86250. var hasShaders = false;
  86251. var processShader = function (sha, shader) {
  86252. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  86253. gltfRuntime.loadedShaderCount++;
  86254. if (shaderString) {
  86255. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  86256. }
  86257. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  86258. onload();
  86259. }
  86260. }, function () {
  86261. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  86262. });
  86263. };
  86264. for (var sha in gltfRuntime.shaders) {
  86265. hasShaders = true;
  86266. var shader = gltfRuntime.shaders[sha];
  86267. if (shader) {
  86268. processShader.bind(this, sha, shader)();
  86269. }
  86270. else {
  86271. BABYLON.Tools.Error("No shader named: " + sha);
  86272. }
  86273. }
  86274. if (!hasShaders) {
  86275. onload();
  86276. }
  86277. };
  86278. ;
  86279. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  86280. var hasBuffers = false;
  86281. var processBuffer = function (buf, buffer) {
  86282. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  86283. gltfRuntime.loadedBufferCount++;
  86284. if (bufferView) {
  86285. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  86286. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  86287. }
  86288. gltfRuntime.loadedBufferViews[buf] = bufferView;
  86289. }
  86290. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  86291. onLoad();
  86292. }
  86293. }, function () {
  86294. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  86295. });
  86296. };
  86297. for (var buf in gltfRuntime.buffers) {
  86298. hasBuffers = true;
  86299. var buffer = gltfRuntime.buffers[buf];
  86300. if (buffer) {
  86301. processBuffer.bind(this, buf, buffer)();
  86302. }
  86303. else {
  86304. BABYLON.Tools.Error("No buffer named: " + buf);
  86305. }
  86306. }
  86307. if (!hasBuffers) {
  86308. onLoad();
  86309. }
  86310. };
  86311. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  86312. var currentScene = gltfRuntime.currentScene;
  86313. if (currentScene) {
  86314. // Only one scene even if multiple scenes are defined
  86315. for (var i = 0; i < currentScene.nodes.length; i++) {
  86316. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  86317. }
  86318. }
  86319. else {
  86320. // Load all scenes
  86321. for (var thing in gltfRuntime.scenes) {
  86322. currentScene = gltfRuntime.scenes[thing];
  86323. for (var i = 0; i < currentScene.nodes.length; i++) {
  86324. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  86325. }
  86326. }
  86327. }
  86328. };
  86329. GLTFLoader.Extensions = {};
  86330. return GLTFLoader;
  86331. }());
  86332. GLTF1.GLTFLoader = GLTFLoader;
  86333. ;
  86334. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  86335. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  86336. })(BABYLON || (BABYLON = {}));
  86337. //# sourceMappingURL=babylon.glTFLoader.js.map
  86338. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  86339. var BABYLON;
  86340. (function (BABYLON) {
  86341. var GLTF1;
  86342. (function (GLTF1) {
  86343. /**
  86344. * Utils functions for GLTF
  86345. */
  86346. var GLTFUtils = /** @class */ (function () {
  86347. function GLTFUtils() {
  86348. }
  86349. /**
  86350. * Sets the given "parameter" matrix
  86351. * @param scene: the {BABYLON.Scene} object
  86352. * @param source: the source node where to pick the matrix
  86353. * @param parameter: the GLTF technique parameter
  86354. * @param uniformName: the name of the shader's uniform
  86355. * @param shaderMaterial: the shader material
  86356. */
  86357. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  86358. var mat = null;
  86359. if (parameter.semantic === "MODEL") {
  86360. mat = source.getWorldMatrix();
  86361. }
  86362. else if (parameter.semantic === "PROJECTION") {
  86363. mat = scene.getProjectionMatrix();
  86364. }
  86365. else if (parameter.semantic === "VIEW") {
  86366. mat = scene.getViewMatrix();
  86367. }
  86368. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  86369. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  86370. }
  86371. else if (parameter.semantic === "MODELVIEW") {
  86372. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  86373. }
  86374. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  86375. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  86376. }
  86377. else if (parameter.semantic === "MODELINVERSE") {
  86378. mat = source.getWorldMatrix().invert();
  86379. }
  86380. else if (parameter.semantic === "VIEWINVERSE") {
  86381. mat = scene.getViewMatrix().invert();
  86382. }
  86383. else if (parameter.semantic === "PROJECTIONINVERSE") {
  86384. mat = scene.getProjectionMatrix().invert();
  86385. }
  86386. else if (parameter.semantic === "MODELVIEWINVERSE") {
  86387. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  86388. }
  86389. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  86390. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  86391. }
  86392. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  86393. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  86394. }
  86395. else {
  86396. debugger;
  86397. }
  86398. if (mat) {
  86399. switch (parameter.type) {
  86400. case GLTF1.EParameterType.FLOAT_MAT2:
  86401. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  86402. break;
  86403. case GLTF1.EParameterType.FLOAT_MAT3:
  86404. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  86405. break;
  86406. case GLTF1.EParameterType.FLOAT_MAT4:
  86407. shaderMaterial.setMatrix(uniformName, mat);
  86408. break;
  86409. default: break;
  86410. }
  86411. }
  86412. };
  86413. /**
  86414. * Sets the given "parameter" matrix
  86415. * @param shaderMaterial: the shader material
  86416. * @param uniform: the name of the shader's uniform
  86417. * @param value: the value of the uniform
  86418. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  86419. */
  86420. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  86421. switch (type) {
  86422. case GLTF1.EParameterType.FLOAT:
  86423. shaderMaterial.setFloat(uniform, value);
  86424. return true;
  86425. case GLTF1.EParameterType.FLOAT_VEC2:
  86426. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  86427. return true;
  86428. case GLTF1.EParameterType.FLOAT_VEC3:
  86429. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  86430. return true;
  86431. case GLTF1.EParameterType.FLOAT_VEC4:
  86432. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  86433. return true;
  86434. default: return false;
  86435. }
  86436. };
  86437. /**
  86438. * If the uri is a base64 string
  86439. * @param uri: the uri to test
  86440. */
  86441. GLTFUtils.IsBase64 = function (uri) {
  86442. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  86443. };
  86444. /**
  86445. * Decode the base64 uri
  86446. * @param uri: the uri to decode
  86447. */
  86448. GLTFUtils.DecodeBase64 = function (uri) {
  86449. var decodedString = atob(uri.split(",")[1]);
  86450. var bufferLength = decodedString.length;
  86451. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  86452. for (var i = 0; i < bufferLength; i++) {
  86453. bufferView[i] = decodedString.charCodeAt(i);
  86454. }
  86455. return bufferView.buffer;
  86456. };
  86457. /**
  86458. * Returns the wrap mode of the texture
  86459. * @param mode: the mode value
  86460. */
  86461. GLTFUtils.GetWrapMode = function (mode) {
  86462. switch (mode) {
  86463. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  86464. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  86465. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  86466. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  86467. }
  86468. };
  86469. /**
  86470. * Returns the byte stride giving an accessor
  86471. * @param accessor: the GLTF accessor objet
  86472. */
  86473. GLTFUtils.GetByteStrideFromType = function (accessor) {
  86474. // Needs this function since "byteStride" isn't requiered in glTF format
  86475. var type = accessor.type;
  86476. switch (type) {
  86477. case "VEC2": return 2;
  86478. case "VEC3": return 3;
  86479. case "VEC4": return 4;
  86480. case "MAT2": return 4;
  86481. case "MAT3": return 9;
  86482. case "MAT4": return 16;
  86483. default: return 1;
  86484. }
  86485. };
  86486. /**
  86487. * Returns the texture filter mode giving a mode value
  86488. * @param mode: the filter mode value
  86489. */
  86490. GLTFUtils.GetTextureFilterMode = function (mode) {
  86491. switch (mode) {
  86492. case GLTF1.ETextureFilterType.LINEAR:
  86493. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  86494. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  86495. case GLTF1.ETextureFilterType.NEAREST:
  86496. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  86497. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  86498. }
  86499. };
  86500. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  86501. var byteOffset = bufferView.byteOffset + byteOffset;
  86502. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  86503. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  86504. throw new Error("Buffer access is out of range");
  86505. }
  86506. var buffer = loadedBufferView.buffer;
  86507. byteOffset += loadedBufferView.byteOffset;
  86508. switch (componentType) {
  86509. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  86510. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  86511. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  86512. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  86513. default: return new Float32Array(buffer, byteOffset, byteLength);
  86514. }
  86515. };
  86516. /**
  86517. * Returns a buffer from its accessor
  86518. * @param gltfRuntime: the GLTF runtime
  86519. * @param accessor: the GLTF accessor
  86520. */
  86521. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  86522. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  86523. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  86524. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  86525. };
  86526. /**
  86527. * Decodes a buffer view into a string
  86528. * @param view: the buffer view
  86529. */
  86530. GLTFUtils.DecodeBufferToText = function (view) {
  86531. var result = "";
  86532. var length = view.byteLength;
  86533. for (var i = 0; i < length; ++i) {
  86534. result += String.fromCharCode(view[i]);
  86535. }
  86536. return result;
  86537. };
  86538. /**
  86539. * Returns the default material of gltf. Related to
  86540. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  86541. * @param scene: the Babylon.js scene
  86542. */
  86543. GLTFUtils.GetDefaultMaterial = function (scene) {
  86544. if (!GLTFUtils._DefaultMaterial) {
  86545. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  86546. "precision highp float;",
  86547. "",
  86548. "uniform mat4 worldView;",
  86549. "uniform mat4 projection;",
  86550. "",
  86551. "attribute vec3 position;",
  86552. "",
  86553. "void main(void)",
  86554. "{",
  86555. " gl_Position = projection * worldView * vec4(position, 1.0);",
  86556. "}"
  86557. ].join("\n");
  86558. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  86559. "precision highp float;",
  86560. "",
  86561. "uniform vec4 u_emission;",
  86562. "",
  86563. "void main(void)",
  86564. "{",
  86565. " gl_FragColor = u_emission;",
  86566. "}"
  86567. ].join("\n");
  86568. var shaderPath = {
  86569. vertex: "GLTFDefaultMaterial",
  86570. fragment: "GLTFDefaultMaterial"
  86571. };
  86572. var options = {
  86573. attributes: ["position"],
  86574. uniforms: ["worldView", "projection", "u_emission"],
  86575. samplers: new Array(),
  86576. needAlphaBlending: false
  86577. };
  86578. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  86579. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  86580. }
  86581. return GLTFUtils._DefaultMaterial;
  86582. };
  86583. // The GLTF default material
  86584. GLTFUtils._DefaultMaterial = null;
  86585. return GLTFUtils;
  86586. }());
  86587. GLTF1.GLTFUtils = GLTFUtils;
  86588. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  86589. })(BABYLON || (BABYLON = {}));
  86590. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  86591. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  86592. var BABYLON;
  86593. (function (BABYLON) {
  86594. var GLTF1;
  86595. (function (GLTF1) {
  86596. var GLTFLoaderExtension = /** @class */ (function () {
  86597. function GLTFLoaderExtension(name) {
  86598. this._name = name;
  86599. }
  86600. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  86601. get: function () {
  86602. return this._name;
  86603. },
  86604. enumerable: true,
  86605. configurable: true
  86606. });
  86607. /**
  86608. * Defines an override for loading the runtime
  86609. * Return true to stop further extensions from loading the runtime
  86610. */
  86611. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  86612. return false;
  86613. };
  86614. /**
  86615. * Defines an onverride for creating gltf runtime
  86616. * Return true to stop further extensions from creating the runtime
  86617. */
  86618. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  86619. return false;
  86620. };
  86621. /**
  86622. * Defines an override for loading buffers
  86623. * Return true to stop further extensions from loading this buffer
  86624. */
  86625. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  86626. return false;
  86627. };
  86628. /**
  86629. * Defines an override for loading texture buffers
  86630. * Return true to stop further extensions from loading this texture data
  86631. */
  86632. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  86633. return false;
  86634. };
  86635. /**
  86636. * Defines an override for creating textures
  86637. * Return true to stop further extensions from loading this texture
  86638. */
  86639. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  86640. return false;
  86641. };
  86642. /**
  86643. * Defines an override for loading shader strings
  86644. * Return true to stop further extensions from loading this shader data
  86645. */
  86646. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  86647. return false;
  86648. };
  86649. /**
  86650. * Defines an override for loading materials
  86651. * Return true to stop further extensions from loading this material
  86652. */
  86653. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  86654. return false;
  86655. };
  86656. // ---------
  86657. // Utilities
  86658. // ---------
  86659. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  86660. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  86661. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  86662. }, function () {
  86663. setTimeout(function () {
  86664. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  86665. });
  86666. });
  86667. };
  86668. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  86669. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  86670. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  86671. }, function () {
  86672. setTimeout(function () {
  86673. onSuccess();
  86674. });
  86675. });
  86676. };
  86677. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  86678. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  86679. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  86680. }, function () {
  86681. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  86682. });
  86683. };
  86684. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  86685. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  86686. };
  86687. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  86688. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  86689. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  86690. }, function () {
  86691. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  86692. });
  86693. };
  86694. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  86695. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  86696. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  86697. }, function () {
  86698. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  86699. });
  86700. };
  86701. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  86702. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  86703. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  86704. }, function () {
  86705. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  86706. });
  86707. };
  86708. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  86709. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  86710. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  86711. }, function () {
  86712. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  86713. });
  86714. };
  86715. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  86716. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  86717. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  86718. if (func(loaderExtension)) {
  86719. return;
  86720. }
  86721. }
  86722. defaultFunc();
  86723. };
  86724. return GLTFLoaderExtension;
  86725. }());
  86726. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  86727. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  86728. })(BABYLON || (BABYLON = {}));
  86729. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  86730. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  86731. var BABYLON;
  86732. (function (BABYLON) {
  86733. var GLTF1;
  86734. (function (GLTF1) {
  86735. var BinaryExtensionBufferName = "binary_glTF";
  86736. ;
  86737. ;
  86738. var GLTFBinaryExtension = /** @class */ (function (_super) {
  86739. __extends(GLTFBinaryExtension, _super);
  86740. function GLTFBinaryExtension() {
  86741. return _super.call(this, "KHR_binary_glTF") || this;
  86742. }
  86743. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  86744. var extensionsUsed = data.json.extensionsUsed;
  86745. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  86746. return false;
  86747. }
  86748. this._bin = data.bin;
  86749. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  86750. return true;
  86751. };
  86752. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  86753. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  86754. return false;
  86755. }
  86756. if (id !== BinaryExtensionBufferName) {
  86757. return false;
  86758. }
  86759. onSuccess(this._bin);
  86760. return true;
  86761. };
  86762. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  86763. var texture = gltfRuntime.textures[id];
  86764. var source = gltfRuntime.images[texture.source];
  86765. if (!source.extensions || !(this.name in source.extensions)) {
  86766. return false;
  86767. }
  86768. var sourceExt = source.extensions[this.name];
  86769. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  86770. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  86771. onSuccess(buffer);
  86772. return true;
  86773. };
  86774. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  86775. var shader = gltfRuntime.shaders[id];
  86776. if (!shader.extensions || !(this.name in shader.extensions)) {
  86777. return false;
  86778. }
  86779. var binaryExtensionShader = shader.extensions[this.name];
  86780. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  86781. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  86782. setTimeout(function () {
  86783. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  86784. onSuccess(shaderString);
  86785. });
  86786. return true;
  86787. };
  86788. return GLTFBinaryExtension;
  86789. }(GLTF1.GLTFLoaderExtension));
  86790. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  86791. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  86792. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  86793. })(BABYLON || (BABYLON = {}));
  86794. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  86795. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  86796. var BABYLON;
  86797. (function (BABYLON) {
  86798. var GLTF1;
  86799. (function (GLTF1) {
  86800. ;
  86801. ;
  86802. ;
  86803. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  86804. __extends(GLTFMaterialsCommonExtension, _super);
  86805. function GLTFMaterialsCommonExtension() {
  86806. return _super.call(this, "KHR_materials_common") || this;
  86807. }
  86808. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  86809. if (!gltfRuntime.extensions)
  86810. return false;
  86811. var extension = gltfRuntime.extensions[this.name];
  86812. if (!extension)
  86813. return false;
  86814. // Create lights
  86815. var lights = extension.lights;
  86816. if (lights) {
  86817. for (var thing in lights) {
  86818. var light = lights[thing];
  86819. switch (light.type) {
  86820. case "ambient":
  86821. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  86822. var ambient = light.ambient;
  86823. if (ambient) {
  86824. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  86825. }
  86826. break;
  86827. case "point":
  86828. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  86829. var point = light.point;
  86830. if (point) {
  86831. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  86832. }
  86833. break;
  86834. case "directional":
  86835. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  86836. var directional = light.directional;
  86837. if (directional) {
  86838. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  86839. }
  86840. break;
  86841. case "spot":
  86842. var spot = light.spot;
  86843. if (spot) {
  86844. 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);
  86845. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  86846. }
  86847. break;
  86848. default:
  86849. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  86850. break;
  86851. }
  86852. }
  86853. }
  86854. return false;
  86855. };
  86856. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  86857. var material = gltfRuntime.materials[id];
  86858. if (!material || !material.extensions)
  86859. return false;
  86860. var extension = material.extensions[this.name];
  86861. if (!extension)
  86862. return false;
  86863. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  86864. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  86865. if (extension.technique === "CONSTANT") {
  86866. standardMaterial.disableLighting = true;
  86867. }
  86868. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  86869. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  86870. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  86871. // Ambient
  86872. if (typeof extension.values.ambient === "string") {
  86873. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  86874. }
  86875. else {
  86876. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  86877. }
  86878. // Diffuse
  86879. if (typeof extension.values.diffuse === "string") {
  86880. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  86881. }
  86882. else {
  86883. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  86884. }
  86885. // Emission
  86886. if (typeof extension.values.emission === "string") {
  86887. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  86888. }
  86889. else {
  86890. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  86891. }
  86892. // Specular
  86893. if (typeof extension.values.specular === "string") {
  86894. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  86895. }
  86896. else {
  86897. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  86898. }
  86899. return true;
  86900. };
  86901. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  86902. // Create buffer from texture url
  86903. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  86904. // Create texture from buffer
  86905. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  86906. }, onError);
  86907. };
  86908. return GLTFMaterialsCommonExtension;
  86909. }(GLTF1.GLTFLoaderExtension));
  86910. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  86911. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  86912. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  86913. })(BABYLON || (BABYLON = {}));
  86914. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  86915. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  86916. var BABYLON;
  86917. (function (BABYLON) {
  86918. var GLTF2;
  86919. (function (GLTF2) {
  86920. /**
  86921. * Enums
  86922. */
  86923. var EComponentType;
  86924. (function (EComponentType) {
  86925. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  86926. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  86927. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  86928. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  86929. EComponentType[EComponentType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  86930. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  86931. })(EComponentType = GLTF2.EComponentType || (GLTF2.EComponentType = {}));
  86932. var EMeshPrimitiveMode;
  86933. (function (EMeshPrimitiveMode) {
  86934. EMeshPrimitiveMode[EMeshPrimitiveMode["POINTS"] = 0] = "POINTS";
  86935. EMeshPrimitiveMode[EMeshPrimitiveMode["LINES"] = 1] = "LINES";
  86936. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_LOOP"] = 2] = "LINE_LOOP";
  86937. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_STRIP"] = 3] = "LINE_STRIP";
  86938. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLES"] = 4] = "TRIANGLES";
  86939. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
  86940. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
  86941. })(EMeshPrimitiveMode = GLTF2.EMeshPrimitiveMode || (GLTF2.EMeshPrimitiveMode = {}));
  86942. var ETextureMagFilter;
  86943. (function (ETextureMagFilter) {
  86944. ETextureMagFilter[ETextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  86945. ETextureMagFilter[ETextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  86946. })(ETextureMagFilter = GLTF2.ETextureMagFilter || (GLTF2.ETextureMagFilter = {}));
  86947. var ETextureMinFilter;
  86948. (function (ETextureMinFilter) {
  86949. ETextureMinFilter[ETextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  86950. ETextureMinFilter[ETextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  86951. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  86952. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  86953. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  86954. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  86955. })(ETextureMinFilter = GLTF2.ETextureMinFilter || (GLTF2.ETextureMinFilter = {}));
  86956. var ETextureWrapMode;
  86957. (function (ETextureWrapMode) {
  86958. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  86959. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  86960. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  86961. })(ETextureWrapMode = GLTF2.ETextureWrapMode || (GLTF2.ETextureWrapMode = {}));
  86962. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  86963. })(BABYLON || (BABYLON = {}));
  86964. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  86965. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  86966. var BABYLON;
  86967. (function (BABYLON) {
  86968. var GLTF2;
  86969. (function (GLTF2) {
  86970. var GLTFLoaderTracker = /** @class */ (function () {
  86971. function GLTFLoaderTracker(onComplete) {
  86972. this._pendingCount = 0;
  86973. this._callback = onComplete;
  86974. }
  86975. GLTFLoaderTracker.prototype._addPendingData = function (data) {
  86976. this._pendingCount++;
  86977. };
  86978. GLTFLoaderTracker.prototype._removePendingData = function (data) {
  86979. if (--this._pendingCount === 0) {
  86980. this._callback();
  86981. }
  86982. };
  86983. return GLTFLoaderTracker;
  86984. }());
  86985. var GLTFLoader = /** @class */ (function () {
  86986. function GLTFLoader() {
  86987. this._disposed = false;
  86988. this._defaultSampler = {};
  86989. this._renderReady = false;
  86990. this._requests = new Array();
  86991. this._renderReadyObservable = new BABYLON.Observable();
  86992. // Count of pending work that needs to complete before the asset is rendered.
  86993. this._renderPendingCount = 0;
  86994. // Count of pending work that needs to complete before the loader is disposed.
  86995. this._loaderPendingCount = 0;
  86996. this._loaderTrackers = new Array();
  86997. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  86998. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  86999. this.compileMaterials = false;
  87000. this.useClipPlane = false;
  87001. this.compileShadowGenerators = false;
  87002. this.onDisposeObservable = new BABYLON.Observable();
  87003. this.onMeshLoadedObservable = new BABYLON.Observable();
  87004. this.onTextureLoadedObservable = new BABYLON.Observable();
  87005. this.onMaterialLoadedObservable = new BABYLON.Observable();
  87006. this.onCompleteObservable = new BABYLON.Observable();
  87007. }
  87008. GLTFLoader.RegisterExtension = function (extension) {
  87009. if (GLTFLoader.Extensions[extension.name]) {
  87010. BABYLON.Tools.Error("Extension with the same name '" + extension.name + "' already exists");
  87011. return;
  87012. }
  87013. GLTFLoader.Extensions[extension.name] = extension;
  87014. // Keep the order of registration so that extensions registered first are called first.
  87015. GLTF2.GLTFLoaderExtension._Extensions.push(extension);
  87016. };
  87017. GLTFLoader.prototype.dispose = function () {
  87018. if (this._disposed) {
  87019. return;
  87020. }
  87021. this._disposed = true;
  87022. this._abortRequests();
  87023. this._releaseResources();
  87024. this.onDisposeObservable.notifyObservers(this);
  87025. };
  87026. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  87027. var _this = this;
  87028. this._loadAsync(meshesNames, scene, data, rootUrl, function () {
  87029. if (onSuccess) {
  87030. onSuccess(_this._getMeshes(), [], _this._getSkeletons());
  87031. }
  87032. }, onProgress, onError);
  87033. };
  87034. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  87035. this._loadAsync(null, scene, data, rootUrl, onSuccess, onProgress, onError);
  87036. };
  87037. GLTFLoader.prototype._loadAsync = function (nodeNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  87038. var _this = this;
  87039. this._babylonScene = scene;
  87040. this._rootUrl = rootUrl;
  87041. this._successCallback = onSuccess;
  87042. this._progressCallback = onProgress;
  87043. this._errorCallback = onError;
  87044. this._tryCatchOnError(function () {
  87045. _this._loadData(data);
  87046. _this._addPendingData(_this);
  87047. _this._loadDefaultScene(nodeNames);
  87048. _this._loadAnimations();
  87049. _this._removePendingData(_this);
  87050. });
  87051. };
  87052. GLTFLoader.prototype._onProgress = function () {
  87053. if (!this._progressCallback) {
  87054. return;
  87055. }
  87056. var lengthComputable = true;
  87057. var loaded = 0;
  87058. var total = 0;
  87059. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  87060. var request = _a[_i];
  87061. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  87062. return;
  87063. }
  87064. lengthComputable = lengthComputable && request._lengthComputable;
  87065. loaded += request._loaded;
  87066. total += request._total;
  87067. }
  87068. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  87069. };
  87070. GLTFLoader.prototype._executeWhenRenderReady = function (func) {
  87071. if (this._renderReady) {
  87072. func();
  87073. }
  87074. else {
  87075. this._renderReadyObservable.add(func);
  87076. }
  87077. };
  87078. GLTFLoader.prototype._onRenderReady = function () {
  87079. this._rootNode.babylonMesh.setEnabled(true);
  87080. this._startAnimations();
  87081. if (this._successCallback) {
  87082. this._successCallback();
  87083. }
  87084. this._renderReadyObservable.notifyObservers(this);
  87085. };
  87086. GLTFLoader.prototype._onComplete = function () {
  87087. this._abortRequests();
  87088. this._releaseResources();
  87089. this.onCompleteObservable.notifyObservers(this);
  87090. };
  87091. GLTFLoader.prototype._loadData = function (data) {
  87092. this._gltf = data.json;
  87093. // Assign the index of each object for convinience.
  87094. GLTFLoader._AssignIndices(this._gltf.accessors);
  87095. GLTFLoader._AssignIndices(this._gltf.animations);
  87096. GLTFLoader._AssignIndices(this._gltf.buffers);
  87097. GLTFLoader._AssignIndices(this._gltf.bufferViews);
  87098. GLTFLoader._AssignIndices(this._gltf.images);
  87099. GLTFLoader._AssignIndices(this._gltf.materials);
  87100. GLTFLoader._AssignIndices(this._gltf.meshes);
  87101. GLTFLoader._AssignIndices(this._gltf.nodes);
  87102. GLTFLoader._AssignIndices(this._gltf.samplers);
  87103. GLTFLoader._AssignIndices(this._gltf.scenes);
  87104. GLTFLoader._AssignIndices(this._gltf.skins);
  87105. GLTFLoader._AssignIndices(this._gltf.textures);
  87106. if (data.bin) {
  87107. var buffers = this._gltf.buffers;
  87108. if (buffers && buffers[0] && !buffers[0].uri) {
  87109. var binaryBuffer = buffers[0];
  87110. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  87111. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  87112. }
  87113. binaryBuffer.loadedData = data.bin;
  87114. }
  87115. else {
  87116. BABYLON.Tools.Warn("Unexpected BIN chunk");
  87117. }
  87118. }
  87119. };
  87120. GLTFLoader.prototype._getMeshes = function () {
  87121. var meshes = new Array();
  87122. // Root mesh is always first.
  87123. meshes.push(this._rootNode.babylonMesh);
  87124. var nodes = this._gltf.nodes;
  87125. if (nodes) {
  87126. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  87127. var node = nodes_1[_i];
  87128. if (node.babylonMesh) {
  87129. meshes.push(node.babylonMesh);
  87130. }
  87131. }
  87132. }
  87133. return meshes;
  87134. };
  87135. GLTFLoader.prototype._getSkeletons = function () {
  87136. var skeletons = new Array();
  87137. var skins = this._gltf.skins;
  87138. if (skins) {
  87139. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  87140. var skin = skins_1[_i];
  87141. if (skin.babylonSkeleton) {
  87142. skeletons.push(skin.babylonSkeleton);
  87143. }
  87144. }
  87145. }
  87146. return skeletons;
  87147. };
  87148. GLTFLoader.prototype._startAnimations = function () {
  87149. var animations = this._gltf.animations;
  87150. if (!animations) {
  87151. return;
  87152. }
  87153. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  87154. var animation = animations_1[_i];
  87155. animation.babylonAnimationGroup.normalize();
  87156. }
  87157. switch (this.animationStartMode) {
  87158. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  87159. // do nothing
  87160. break;
  87161. }
  87162. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  87163. var animation = animations[0];
  87164. animation.babylonAnimationGroup.start(true);
  87165. break;
  87166. }
  87167. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  87168. for (var _a = 0, animations_2 = animations; _a < animations_2.length; _a++) {
  87169. var animation = animations_2[_a];
  87170. animation.babylonAnimationGroup.start(true);
  87171. }
  87172. break;
  87173. }
  87174. default: {
  87175. BABYLON.Tools.Error("Invalid animation start mode " + this.animationStartMode);
  87176. return;
  87177. }
  87178. }
  87179. };
  87180. GLTFLoader.prototype._loadDefaultScene = function (nodeNames) {
  87181. var scene = GLTFLoader._GetProperty(this._gltf.scenes, this._gltf.scene || 0);
  87182. if (!scene) {
  87183. throw new Error("Failed to find scene " + (this._gltf.scene || 0));
  87184. }
  87185. this._loadScene("#/scenes/" + scene.index, scene, nodeNames);
  87186. };
  87187. GLTFLoader.prototype._loadScene = function (context, scene, nodeNames) {
  87188. var _this = this;
  87189. this._rootNode = { babylonMesh: new BABYLON.Mesh("__root__", this._babylonScene) };
  87190. switch (this.coordinateSystemMode) {
  87191. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  87192. if (!this._babylonScene.useRightHandedSystem) {
  87193. this._rootNode.rotation = [0, 1, 0, 0];
  87194. this._rootNode.scale = [1, 1, -1];
  87195. this._loadTransform(this._rootNode);
  87196. }
  87197. break;
  87198. }
  87199. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  87200. this._babylonScene.useRightHandedSystem = true;
  87201. break;
  87202. }
  87203. default: {
  87204. BABYLON.Tools.Error("Invalid coordinate system mode " + this.coordinateSystemMode);
  87205. return;
  87206. }
  87207. }
  87208. this.onMeshLoadedObservable.notifyObservers(this._rootNode.babylonMesh);
  87209. var nodeIndices = scene.nodes;
  87210. this._traverseNodes(context, nodeIndices, function (node, parentNode) {
  87211. node.parent = parentNode;
  87212. return true;
  87213. }, this._rootNode);
  87214. if (nodeNames) {
  87215. if (!(nodeNames instanceof Array)) {
  87216. nodeNames = [nodeNames];
  87217. }
  87218. var filteredNodeIndices_1 = new Array();
  87219. this._traverseNodes(context, nodeIndices, function (node) {
  87220. if (nodeNames.indexOf(node.name) !== -1) {
  87221. filteredNodeIndices_1.push(node.index);
  87222. node.parent = _this._rootNode;
  87223. return false;
  87224. }
  87225. return true;
  87226. }, this._rootNode);
  87227. nodeIndices = filteredNodeIndices_1;
  87228. }
  87229. for (var _i = 0, nodeIndices_1 = nodeIndices; _i < nodeIndices_1.length; _i++) {
  87230. var index = nodeIndices_1[_i];
  87231. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  87232. if (!node) {
  87233. throw new Error(context + ": Failed to find node " + index);
  87234. }
  87235. this._loadNode("#/nodes/" + index, node);
  87236. }
  87237. // Disable the root mesh until the asset is ready to render.
  87238. this._rootNode.babylonMesh.setEnabled(false);
  87239. };
  87240. GLTFLoader.prototype._loadNode = function (context, node) {
  87241. if (GLTF2.GLTFLoaderExtension.LoadNode(this, context, node)) {
  87242. return;
  87243. }
  87244. node.babylonMesh = new BABYLON.Mesh(node.name || "mesh" + node.index, this._babylonScene);
  87245. this._loadTransform(node);
  87246. if (node.mesh != null) {
  87247. var mesh = GLTFLoader._GetProperty(this._gltf.meshes, node.mesh);
  87248. if (!mesh) {
  87249. throw new Error(context + ": Failed to find mesh " + node.mesh);
  87250. }
  87251. this._loadMesh("#/meshes/" + node.mesh, node, mesh);
  87252. }
  87253. node.babylonMesh.parent = node.parent.babylonMesh;
  87254. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  87255. node.babylonAnimationTargets.push(node.babylonMesh);
  87256. if (node.skin != null) {
  87257. var skin_1 = GLTFLoader._GetProperty(this._gltf.skins, node.skin);
  87258. if (!skin_1) {
  87259. throw new Error(context + ": Failed to find skin " + node.skin);
  87260. }
  87261. this._loadSkinAsync("#/skins/" + node.skin, skin_1, function () {
  87262. node.babylonMesh.skeleton = skin_1.babylonSkeleton;
  87263. node.babylonMesh._refreshBoundingInfo(true);
  87264. });
  87265. node.babylonMesh.parent = this._rootNode.babylonMesh;
  87266. node.babylonMesh.position = BABYLON.Vector3.Zero();
  87267. node.babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  87268. node.babylonMesh.scaling = BABYLON.Vector3.One();
  87269. }
  87270. if (node.camera != null) {
  87271. // TODO: handle cameras
  87272. }
  87273. if (node.children) {
  87274. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  87275. var index = _a[_i];
  87276. var childNode = GLTFLoader._GetProperty(this._gltf.nodes, index);
  87277. if (!childNode) {
  87278. throw new Error(context + ": Failed to find child node " + index);
  87279. }
  87280. this._loadNode("#/nodes/" + index, childNode);
  87281. }
  87282. }
  87283. this.onMeshLoadedObservable.notifyObservers(node.babylonMesh);
  87284. };
  87285. GLTFLoader.prototype._loadMesh = function (context, node, mesh) {
  87286. var _this = this;
  87287. var primitives = mesh.primitives;
  87288. if (!primitives || primitives.length === 0) {
  87289. throw new Error(context + ": Primitives are missing");
  87290. }
  87291. this._createMorphTargets(context, node, mesh);
  87292. this._loadAllVertexDataAsync(context, mesh, function () {
  87293. _this._loadMorphTargets(context, node, mesh);
  87294. var vertexData = new BABYLON.VertexData();
  87295. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  87296. var primitive = primitives_1[_i];
  87297. vertexData.merge(primitive.vertexData);
  87298. }
  87299. node.babylonMesh.hasVertexAlpha = mesh.hasVertexAlpha;
  87300. new BABYLON.Geometry(node.babylonMesh.name, _this._babylonScene, vertexData, false, node.babylonMesh);
  87301. // TODO: optimize this so that sub meshes can be created without being overwritten after setting vertex data.
  87302. // Sub meshes must be cleared and created after setting vertex data because of mesh._createGlobalSubMesh.
  87303. node.babylonMesh.subMeshes = [];
  87304. var verticesStart = 0;
  87305. var indicesStart = 0;
  87306. for (var index = 0; index < primitives.length; index++) {
  87307. var vertexData_1 = primitives[index].vertexData;
  87308. var verticesCount = vertexData_1.positions.length;
  87309. var indicesCount = vertexData_1.indices.length;
  87310. BABYLON.SubMesh.AddToMesh(index, verticesStart, verticesCount, indicesStart, indicesCount, node.babylonMesh);
  87311. verticesStart += verticesCount;
  87312. indicesStart += indicesCount;
  87313. }
  87314. ;
  87315. });
  87316. if (primitives.length === 1) {
  87317. var primitive = primitives[0];
  87318. if (primitive.material == null) {
  87319. node.babylonMesh.material = this._getDefaultMaterial();
  87320. }
  87321. else {
  87322. var material = GLTFLoader._GetProperty(this._gltf.materials, primitive.material);
  87323. if (!material) {
  87324. throw new Error(context + ": Failed to find material " + primitive.material);
  87325. }
  87326. this._loadMaterial("#/materials/" + material.index, material, function (babylonMaterial, isNew) {
  87327. if (isNew) {
  87328. _this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  87329. }
  87330. node.babylonMesh.material = babylonMaterial;
  87331. });
  87332. }
  87333. }
  87334. else {
  87335. var multiMaterial = new BABYLON.MultiMaterial(node.babylonMesh.name, this._babylonScene);
  87336. node.babylonMesh.material = multiMaterial;
  87337. var subMaterials_1 = multiMaterial.subMaterials;
  87338. var _loop_1 = function (index) {
  87339. var primitive = primitives[index];
  87340. if (primitive.material == null) {
  87341. subMaterials_1[index] = this_1._getDefaultMaterial();
  87342. }
  87343. else {
  87344. var material = GLTFLoader._GetProperty(this_1._gltf.materials, primitive.material);
  87345. if (!material) {
  87346. throw new Error(context + ": Failed to find material " + primitive.material);
  87347. }
  87348. this_1._loadMaterial("#/materials/" + material.index, material, function (babylonMaterial, isNew) {
  87349. if (isNew) {
  87350. _this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  87351. }
  87352. subMaterials_1[index] = babylonMaterial;
  87353. });
  87354. }
  87355. };
  87356. var this_1 = this;
  87357. for (var index = 0; index < primitives.length; index++) {
  87358. _loop_1(index);
  87359. }
  87360. ;
  87361. }
  87362. };
  87363. GLTFLoader.prototype._loadAllVertexDataAsync = function (context, mesh, onSuccess) {
  87364. var primitives = mesh.primitives;
  87365. var numRemainingPrimitives = primitives.length;
  87366. var _loop_2 = function (index) {
  87367. var primitive = primitives[index];
  87368. this_2._loadVertexDataAsync(context + "/primitive/" + index, mesh, primitive, function (vertexData) {
  87369. primitive.vertexData = vertexData;
  87370. if (--numRemainingPrimitives === 0) {
  87371. onSuccess();
  87372. }
  87373. });
  87374. };
  87375. var this_2 = this;
  87376. for (var index = 0; index < primitives.length; index++) {
  87377. _loop_2(index);
  87378. }
  87379. };
  87380. /**
  87381. * Converts a data bufferview into a Float4 Texture Coordinate Array, based on the accessor component type
  87382. * @param {ArrayBufferView} data
  87383. * @param {IGLTFAccessor} accessor
  87384. */
  87385. GLTFLoader.prototype._convertToFloat4TextureCoordArray = function (context, data, accessor) {
  87386. if (accessor.componentType == GLTF2.EComponentType.FLOAT) {
  87387. return data;
  87388. }
  87389. var buffer = data;
  87390. var factor = 1;
  87391. switch (accessor.componentType) {
  87392. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  87393. factor = 1 / 255;
  87394. break;
  87395. }
  87396. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  87397. factor = 1 / 65535;
  87398. break;
  87399. }
  87400. default: {
  87401. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  87402. }
  87403. }
  87404. var result = new Float32Array(accessor.count * 2);
  87405. for (var i = 0; i < result.length; ++i) {
  87406. result[i] = buffer[i] * factor;
  87407. }
  87408. return result;
  87409. };
  87410. /**
  87411. * Converts a data bufferview into a Float4 Color Array, based on the accessor component type
  87412. * @param {ArrayBufferView} data
  87413. * @param {IGLTFAccessor} accessor
  87414. */
  87415. GLTFLoader.prototype._convertToFloat4ColorArray = function (context, data, accessor) {
  87416. var colorComponentCount = GLTFLoader._GetNumComponents(context, accessor.type);
  87417. if (colorComponentCount === 4 && accessor.componentType === GLTF2.EComponentType.FLOAT) {
  87418. return data;
  87419. }
  87420. var buffer = data;
  87421. var factor = 1;
  87422. switch (accessor.componentType) {
  87423. case GLTF2.EComponentType.FLOAT: {
  87424. factor = 1;
  87425. break;
  87426. }
  87427. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  87428. factor = 1 / 255;
  87429. break;
  87430. }
  87431. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  87432. factor = 1 / 65535;
  87433. break;
  87434. }
  87435. default: {
  87436. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  87437. }
  87438. }
  87439. var result = new Float32Array(accessor.count * 4);
  87440. if (colorComponentCount === 4) {
  87441. for (var i = 0; i < result.length; ++i) {
  87442. result[i] = buffer[i] * factor;
  87443. }
  87444. }
  87445. else {
  87446. var offset = 0;
  87447. for (var i = 0; i < result.length; ++i) {
  87448. if ((i + 1) % 4 === 0) {
  87449. result[i] = 1;
  87450. }
  87451. else {
  87452. result[i] = buffer[offset++] * factor;
  87453. }
  87454. }
  87455. }
  87456. return result;
  87457. };
  87458. GLTFLoader.prototype._loadVertexDataAsync = function (context, mesh, primitive, onSuccess) {
  87459. var _this = this;
  87460. var attributes = primitive.attributes;
  87461. if (!attributes) {
  87462. throw new Error(context + ": Attributes are missing");
  87463. }
  87464. if (primitive.mode && primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  87465. // TODO: handle other primitive modes
  87466. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  87467. }
  87468. var vertexData = new BABYLON.VertexData();
  87469. var numRemainingAttributes = Object.keys(attributes).length;
  87470. var _loop_3 = function (attribute) {
  87471. var accessor = GLTFLoader._GetProperty(this_3._gltf.accessors, attributes[attribute]);
  87472. if (!accessor) {
  87473. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  87474. }
  87475. this_3._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  87476. switch (attribute) {
  87477. case "POSITION": {
  87478. vertexData.positions = data;
  87479. break;
  87480. }
  87481. case "NORMAL": {
  87482. vertexData.normals = data;
  87483. break;
  87484. }
  87485. case "TANGENT": {
  87486. vertexData.tangents = data;
  87487. break;
  87488. }
  87489. case "TEXCOORD_0": {
  87490. vertexData.uvs = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  87491. break;
  87492. }
  87493. case "TEXCOORD_1": {
  87494. vertexData.uvs2 = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  87495. break;
  87496. }
  87497. case "JOINTS_0": {
  87498. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  87499. break;
  87500. }
  87501. case "WEIGHTS_0": {
  87502. //TODO: need to add support for normalized weights.
  87503. vertexData.matricesWeights = data;
  87504. break;
  87505. }
  87506. case "COLOR_0": {
  87507. vertexData.colors = _this._convertToFloat4ColorArray(context, data, accessor);
  87508. var hasVertexAlpha = GLTFLoader._GetNumComponents(context, accessor.type) === 4;
  87509. if (!mesh.hasVertexAlpha && hasVertexAlpha) {
  87510. mesh.hasVertexAlpha = hasVertexAlpha;
  87511. }
  87512. break;
  87513. }
  87514. default: {
  87515. BABYLON.Tools.Warn(context + ": Ignoring unrecognized attribute '" + attribute + "'");
  87516. break;
  87517. }
  87518. }
  87519. if (--numRemainingAttributes === 0) {
  87520. if (primitive.indices == null) {
  87521. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  87522. for (var i = 0; i < vertexData.indices.length; i++) {
  87523. vertexData.indices[i] = i;
  87524. }
  87525. onSuccess(vertexData);
  87526. }
  87527. else {
  87528. var indicesAccessor = GLTFLoader._GetProperty(_this._gltf.accessors, primitive.indices);
  87529. if (!indicesAccessor) {
  87530. throw new Error(context + ": Failed to find indices accessor " + primitive.indices);
  87531. }
  87532. _this._loadAccessorAsync("#/accessors/" + indicesAccessor.index, indicesAccessor, function (data) {
  87533. vertexData.indices = data;
  87534. onSuccess(vertexData);
  87535. });
  87536. }
  87537. }
  87538. });
  87539. };
  87540. var this_3 = this;
  87541. for (var attribute in attributes) {
  87542. _loop_3(attribute);
  87543. }
  87544. };
  87545. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh) {
  87546. var primitives = mesh.primitives;
  87547. var targets = primitives[0].targets;
  87548. if (!targets) {
  87549. return;
  87550. }
  87551. for (var _i = 0, primitives_2 = primitives; _i < primitives_2.length; _i++) {
  87552. var primitive = primitives_2[_i];
  87553. if (!primitive.targets || primitive.targets.length != targets.length) {
  87554. throw new Error(context + ": All primitives are required to list the same number of targets");
  87555. }
  87556. }
  87557. var morphTargetManager = new BABYLON.MorphTargetManager();
  87558. node.babylonMesh.morphTargetManager = morphTargetManager;
  87559. for (var index = 0; index < targets.length; index++) {
  87560. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  87561. morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  87562. }
  87563. };
  87564. GLTFLoader.prototype._loadMorphTargets = function (context, node, mesh) {
  87565. var morphTargetManager = node.babylonMesh.morphTargetManager;
  87566. if (!morphTargetManager) {
  87567. return;
  87568. }
  87569. this._loadAllMorphTargetVertexDataAsync(context, node, mesh, function () {
  87570. var numTargets = morphTargetManager.numTargets;
  87571. for (var index = 0; index < numTargets; index++) {
  87572. var vertexData = new BABYLON.VertexData();
  87573. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  87574. var primitive = _a[_i];
  87575. vertexData.merge(primitive.targetsVertexData[index], { tangentLength: 3 });
  87576. }
  87577. if (!vertexData.positions) {
  87578. throw new Error(context + ": Positions are missing");
  87579. }
  87580. var target = morphTargetManager.getTarget(index);
  87581. target.setPositions(vertexData.positions);
  87582. target.setNormals(vertexData.normals);
  87583. target.setTangents(vertexData.tangents);
  87584. }
  87585. });
  87586. };
  87587. GLTFLoader.prototype._loadAllMorphTargetVertexDataAsync = function (context, node, mesh, onSuccess) {
  87588. var numRemainingTargets = mesh.primitives.length * node.babylonMesh.morphTargetManager.numTargets;
  87589. var _loop_4 = function (primitive) {
  87590. var targets = primitive.targets;
  87591. primitive.targetsVertexData = new Array(targets.length);
  87592. var _loop_5 = function (index) {
  87593. this_4._loadMorphTargetVertexDataAsync(context + "/targets/" + index, primitive.vertexData, targets[index], function (vertexData) {
  87594. primitive.targetsVertexData[index] = vertexData;
  87595. if (--numRemainingTargets === 0) {
  87596. onSuccess();
  87597. }
  87598. });
  87599. };
  87600. for (var index = 0; index < targets.length; index++) {
  87601. _loop_5(index);
  87602. }
  87603. };
  87604. var this_4 = this;
  87605. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  87606. var primitive = _a[_i];
  87607. _loop_4(primitive);
  87608. }
  87609. };
  87610. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, vertexData, attributes, onSuccess) {
  87611. var targetVertexData = new BABYLON.VertexData();
  87612. var numRemainingAttributes = Object.keys(attributes).length;
  87613. var _loop_6 = function (attribute) {
  87614. var accessor = GLTFLoader._GetProperty(this_5._gltf.accessors, attributes[attribute]);
  87615. if (!accessor) {
  87616. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  87617. }
  87618. this_5._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  87619. // glTF stores morph target information as deltas while babylon.js expects the final data.
  87620. // As a result we have to add the original data to the delta to calculate the final data.
  87621. var values = data;
  87622. switch (attribute) {
  87623. case "POSITION": {
  87624. for (var i = 0; i < values.length; i++) {
  87625. values[i] += vertexData.positions[i];
  87626. }
  87627. targetVertexData.positions = values;
  87628. break;
  87629. }
  87630. case "NORMAL": {
  87631. for (var i = 0; i < values.length; i++) {
  87632. values[i] += vertexData.normals[i];
  87633. }
  87634. targetVertexData.normals = values;
  87635. break;
  87636. }
  87637. case "TANGENT": {
  87638. // Tangent data for morph targets is stored as xyz delta.
  87639. // The vertexData.tangent is stored as xyzw.
  87640. // So we need to skip every fourth vertexData.tangent.
  87641. for (var i = 0, j = 0; i < values.length; i++, j++) {
  87642. values[i] += vertexData.tangents[j];
  87643. if ((i + 1) % 3 == 0) {
  87644. j++;
  87645. }
  87646. }
  87647. targetVertexData.tangents = values;
  87648. break;
  87649. }
  87650. default: {
  87651. BABYLON.Tools.Warn(context + ": Ignoring unrecognized attribute '" + attribute + "'");
  87652. break;
  87653. }
  87654. }
  87655. if (--numRemainingAttributes === 0) {
  87656. onSuccess(targetVertexData);
  87657. }
  87658. });
  87659. };
  87660. var this_5 = this;
  87661. for (var attribute in attributes) {
  87662. _loop_6(attribute);
  87663. }
  87664. };
  87665. GLTFLoader.prototype._loadTransform = function (node) {
  87666. var position = BABYLON.Vector3.Zero();
  87667. var rotation = BABYLON.Quaternion.Identity();
  87668. var scaling = BABYLON.Vector3.One();
  87669. if (node.matrix) {
  87670. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  87671. matrix.decompose(scaling, rotation, position);
  87672. }
  87673. else {
  87674. if (node.translation)
  87675. position = BABYLON.Vector3.FromArray(node.translation);
  87676. if (node.rotation)
  87677. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  87678. if (node.scale)
  87679. scaling = BABYLON.Vector3.FromArray(node.scale);
  87680. }
  87681. node.babylonMesh.position = position;
  87682. node.babylonMesh.rotationQuaternion = rotation;
  87683. node.babylonMesh.scaling = scaling;
  87684. };
  87685. GLTFLoader.prototype._loadSkinAsync = function (context, skin, onSuccess) {
  87686. var _this = this;
  87687. if (skin.babylonSkeleton) {
  87688. onSuccess();
  87689. return;
  87690. }
  87691. var skeletonId = "skeleton" + skin.index;
  87692. skin.babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  87693. if (skin.inverseBindMatrices == null) {
  87694. this._loadBones(context, skin, null);
  87695. onSuccess();
  87696. }
  87697. else {
  87698. var accessor = GLTFLoader._GetProperty(this._gltf.accessors, skin.inverseBindMatrices);
  87699. if (!accessor) {
  87700. throw new Error(context + ": Failed to find inverse bind matrices attribute " + skin.inverseBindMatrices);
  87701. }
  87702. this._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  87703. _this._loadBones(context, skin, data);
  87704. onSuccess();
  87705. });
  87706. }
  87707. };
  87708. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  87709. var babylonBone = new BABYLON.Bone(node.name || "bone" + node.index, skin.babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  87710. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  87711. node.babylonAnimationTargets.push(babylonBone);
  87712. return babylonBone;
  87713. };
  87714. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatrixData) {
  87715. var babylonBones = {};
  87716. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  87717. var index = _a[_i];
  87718. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  87719. if (!node) {
  87720. throw new Error(context + ": Failed to find joint " + index);
  87721. }
  87722. this._loadBone(node, skin, inverseBindMatrixData, babylonBones);
  87723. }
  87724. };
  87725. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatrixData, babylonBones) {
  87726. var babylonBone = babylonBones[node.index];
  87727. if (babylonBone) {
  87728. return babylonBone;
  87729. }
  87730. var boneIndex = skin.joints.indexOf(node.index);
  87731. var baseMatrix = BABYLON.Matrix.Identity();
  87732. if (inverseBindMatrixData && boneIndex !== -1) {
  87733. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatrixData, boneIndex * 16);
  87734. baseMatrix.invertToRef(baseMatrix);
  87735. }
  87736. var babylonParentBone = null;
  87737. if (node.parent !== this._rootNode) {
  87738. babylonParentBone = this._loadBone(node.parent, skin, inverseBindMatrixData, babylonBones);
  87739. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  87740. }
  87741. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  87742. babylonBones[node.index] = babylonBone;
  87743. return babylonBone;
  87744. };
  87745. GLTFLoader.prototype._getNodeMatrix = function (node) {
  87746. return node.matrix ?
  87747. BABYLON.Matrix.FromArray(node.matrix) :
  87748. 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());
  87749. };
  87750. GLTFLoader.prototype._traverseNodes = function (context, indices, action, parentNode) {
  87751. for (var _i = 0, indices_1 = indices; _i < indices_1.length; _i++) {
  87752. var index = indices_1[_i];
  87753. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  87754. if (!node) {
  87755. throw new Error(context + ": Failed to find node " + index);
  87756. }
  87757. this._traverseNode(context, node, action, parentNode);
  87758. }
  87759. };
  87760. GLTFLoader.prototype._traverseNode = function (context, node, action, parentNode) {
  87761. if (GLTF2.GLTFLoaderExtension.TraverseNode(this, context, node, action, parentNode)) {
  87762. return;
  87763. }
  87764. if (!action(node, parentNode)) {
  87765. return;
  87766. }
  87767. if (node.children) {
  87768. this._traverseNodes(context, node.children, action, node);
  87769. }
  87770. };
  87771. GLTFLoader.prototype._loadAnimations = function () {
  87772. var animations = this._gltf.animations;
  87773. if (!animations) {
  87774. return;
  87775. }
  87776. for (var index = 0; index < animations.length; index++) {
  87777. var animation = animations[index];
  87778. this._loadAnimation("#/animations/" + index, animation);
  87779. }
  87780. };
  87781. GLTFLoader.prototype._loadAnimation = function (context, animation) {
  87782. animation.babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation.index, this._babylonScene);
  87783. for (var index = 0; index < animation.channels.length; index++) {
  87784. var channel = GLTFLoader._GetProperty(animation.channels, index);
  87785. if (!channel) {
  87786. throw new Error(context + ": Failed to find channel " + index);
  87787. }
  87788. var sampler = GLTFLoader._GetProperty(animation.samplers, channel.sampler);
  87789. if (!sampler) {
  87790. throw new Error(context + ": Failed to find sampler " + channel.sampler);
  87791. }
  87792. this._loadAnimationChannel(animation, context + "/channels/" + index, channel, context + "/samplers/" + channel.sampler, sampler);
  87793. }
  87794. };
  87795. GLTFLoader.prototype._loadAnimationChannel = function (animation, channelContext, channel, samplerContext, sampler) {
  87796. var targetNode = GLTFLoader._GetProperty(this._gltf.nodes, channel.target.node);
  87797. if (!targetNode) {
  87798. throw new Error(channelContext + ": Failed to find target node " + channel.target.node);
  87799. }
  87800. var targetPath;
  87801. var animationType;
  87802. switch (channel.target.path) {
  87803. case "translation": {
  87804. targetPath = "position";
  87805. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  87806. break;
  87807. }
  87808. case "rotation": {
  87809. targetPath = "rotationQuaternion";
  87810. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  87811. break;
  87812. }
  87813. case "scale": {
  87814. targetPath = "scaling";
  87815. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  87816. break;
  87817. }
  87818. case "weights": {
  87819. targetPath = "influence";
  87820. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  87821. break;
  87822. }
  87823. default: {
  87824. throw new Error(channelContext + ": Invalid target path " + channel.target.path);
  87825. }
  87826. }
  87827. var inputData;
  87828. var outputData;
  87829. var checkSuccess = function () {
  87830. if (!inputData || !outputData) {
  87831. return;
  87832. }
  87833. var outputBufferOffset = 0;
  87834. var getNextOutputValue;
  87835. switch (targetPath) {
  87836. case "position": {
  87837. getNextOutputValue = function () {
  87838. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  87839. outputBufferOffset += 3;
  87840. return value;
  87841. };
  87842. break;
  87843. }
  87844. case "rotationQuaternion": {
  87845. getNextOutputValue = function () {
  87846. var value = BABYLON.Quaternion.FromArray(outputData, outputBufferOffset);
  87847. outputBufferOffset += 4;
  87848. return value;
  87849. };
  87850. break;
  87851. }
  87852. case "scaling": {
  87853. getNextOutputValue = function () {
  87854. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  87855. outputBufferOffset += 3;
  87856. return value;
  87857. };
  87858. break;
  87859. }
  87860. case "influence": {
  87861. getNextOutputValue = function () {
  87862. var numTargets = targetNode.babylonMesh.morphTargetManager.numTargets;
  87863. var value = new Array(numTargets);
  87864. for (var i = 0; i < numTargets; i++) {
  87865. value[i] = outputData[outputBufferOffset++];
  87866. }
  87867. return value;
  87868. };
  87869. break;
  87870. }
  87871. }
  87872. sampler.interpolation = sampler.interpolation || "LINEAR";
  87873. var getNextKey;
  87874. switch (sampler.interpolation) {
  87875. case "STEP": {
  87876. getNextKey = function (frameIndex) { return ({
  87877. frame: inputData[frameIndex],
  87878. value: getNextOutputValue(),
  87879. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  87880. }); };
  87881. break;
  87882. }
  87883. case "LINEAR": {
  87884. getNextKey = function (frameIndex) { return ({
  87885. frame: inputData[frameIndex],
  87886. value: getNextOutputValue()
  87887. }); };
  87888. break;
  87889. }
  87890. case "CUBICSPLINE": {
  87891. getNextKey = function (frameIndex) { return ({
  87892. frame: inputData[frameIndex],
  87893. inTangent: getNextOutputValue(),
  87894. value: getNextOutputValue(),
  87895. outTangent: getNextOutputValue()
  87896. }); };
  87897. break;
  87898. }
  87899. default: {
  87900. throw new Error(samplerContext + ": Invalid interpolation " + sampler.interpolation);
  87901. }
  87902. }
  87903. ;
  87904. var keys;
  87905. if (inputData.length === 1) {
  87906. var key = getNextKey(0);
  87907. keys = [
  87908. { frame: key.frame, value: key.value },
  87909. { frame: key.frame + 1, value: key.value }
  87910. ];
  87911. }
  87912. else {
  87913. keys = new Array(inputData.length);
  87914. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  87915. keys[frameIndex] = getNextKey(frameIndex);
  87916. }
  87917. }
  87918. if (targetPath === "influence") {
  87919. var morphTargetManager = targetNode.babylonMesh.morphTargetManager;
  87920. var _loop_7 = function (targetIndex) {
  87921. var morphTarget = morphTargetManager.getTarget(targetIndex);
  87922. var animationName = animation.babylonAnimationGroup.name + "_channel" + animation.babylonAnimationGroup.targetedAnimations.length;
  87923. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  87924. babylonAnimation.setKeys(keys.map(function (key) { return ({
  87925. frame: key.frame,
  87926. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  87927. value: key.value[targetIndex],
  87928. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  87929. }); }));
  87930. animation.babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTarget);
  87931. };
  87932. for (var targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) {
  87933. _loop_7(targetIndex);
  87934. }
  87935. }
  87936. else {
  87937. var animationName = animation.babylonAnimationGroup.name + "_channel" + animation.babylonAnimationGroup.targetedAnimations.length;
  87938. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  87939. babylonAnimation.setKeys(keys);
  87940. if (targetNode.babylonAnimationTargets) {
  87941. for (var _i = 0, _a = targetNode.babylonAnimationTargets; _i < _a.length; _i++) {
  87942. var target = _a[_i];
  87943. animation.babylonAnimationGroup.addTargetedAnimation(babylonAnimation, target);
  87944. }
  87945. }
  87946. }
  87947. };
  87948. var inputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.input);
  87949. if (!inputAccessor) {
  87950. throw new Error(samplerContext + ": Failed to find input accessor " + sampler.input);
  87951. }
  87952. this._loadAccessorAsync("#/accessors/" + inputAccessor.index, inputAccessor, function (data) {
  87953. inputData = data;
  87954. checkSuccess();
  87955. });
  87956. var outputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.output);
  87957. if (!outputAccessor) {
  87958. throw new Error(samplerContext + ": Failed to find output accessor " + sampler.output);
  87959. }
  87960. this._loadAccessorAsync("#/accessors/" + outputAccessor.index, outputAccessor, function (data) {
  87961. outputData = data;
  87962. checkSuccess();
  87963. });
  87964. };
  87965. GLTFLoader.prototype._loadBufferAsync = function (context, buffer, onSuccess) {
  87966. var _this = this;
  87967. this._addPendingData(buffer);
  87968. if (buffer.loadedData) {
  87969. onSuccess(buffer.loadedData);
  87970. this._removePendingData(buffer);
  87971. }
  87972. else if (buffer.loadedObservable) {
  87973. buffer.loadedObservable.add(function (buffer) {
  87974. onSuccess(buffer.loadedData);
  87975. _this._removePendingData(buffer);
  87976. });
  87977. }
  87978. else {
  87979. if (!buffer.uri) {
  87980. throw new Error(context + ": Uri is missing");
  87981. }
  87982. buffer.loadedObservable = new BABYLON.Observable();
  87983. buffer.loadedObservable.add(function (buffer) {
  87984. onSuccess(buffer.loadedData);
  87985. _this._removePendingData(buffer);
  87986. });
  87987. this._loadUriAsync(context, buffer.uri, function (data) {
  87988. buffer.loadedData = data;
  87989. buffer.loadedObservable.notifyObservers(buffer);
  87990. buffer.loadedObservable = undefined;
  87991. });
  87992. }
  87993. };
  87994. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView, onSuccess) {
  87995. var buffer = GLTFLoader._GetProperty(this._gltf.buffers, bufferView.buffer);
  87996. if (!buffer) {
  87997. throw new Error(context + ": Failed to find buffer " + bufferView.buffer);
  87998. }
  87999. this._loadBufferAsync("#/buffers/" + buffer.index, buffer, function (bufferData) {
  88000. var data;
  88001. try {
  88002. data = new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  88003. }
  88004. catch (e) {
  88005. throw new Error(context + ": " + e.message);
  88006. }
  88007. onSuccess(data);
  88008. });
  88009. };
  88010. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor, onSuccess) {
  88011. var _this = this;
  88012. if (accessor.sparse) {
  88013. throw new Error(context + ": Sparse accessors are not currently supported");
  88014. }
  88015. var bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, accessor.bufferView);
  88016. if (!bufferView) {
  88017. throw new Error(context + ": Failed to find buffer view " + accessor.bufferView);
  88018. }
  88019. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, function (bufferViewData) {
  88020. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  88021. var data;
  88022. var byteOffset = accessor.byteOffset || 0;
  88023. var byteStride = bufferView.byteStride;
  88024. if (byteStride === 0) {
  88025. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  88026. }
  88027. try {
  88028. switch (accessor.componentType) {
  88029. case GLTF2.EComponentType.BYTE: {
  88030. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  88031. break;
  88032. }
  88033. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  88034. data = _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  88035. break;
  88036. }
  88037. case GLTF2.EComponentType.SHORT: {
  88038. data = _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  88039. break;
  88040. }
  88041. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  88042. data = _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  88043. break;
  88044. }
  88045. case GLTF2.EComponentType.UNSIGNED_INT: {
  88046. data = _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  88047. break;
  88048. }
  88049. case GLTF2.EComponentType.FLOAT: {
  88050. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  88051. break;
  88052. }
  88053. default: {
  88054. throw new Error(context + ": Invalid component type " + accessor.componentType);
  88055. }
  88056. }
  88057. }
  88058. catch (e) {
  88059. throw new Error(context + ": " + e);
  88060. }
  88061. onSuccess(data);
  88062. });
  88063. };
  88064. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  88065. byteOffset += data.byteOffset;
  88066. var targetLength = count * numComponents;
  88067. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  88068. return new typedArray(data.buffer, byteOffset, targetLength);
  88069. }
  88070. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  88071. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  88072. var targetBuffer = new typedArray(targetLength);
  88073. var sourceIndex = 0;
  88074. var targetIndex = 0;
  88075. while (targetIndex < targetLength) {
  88076. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  88077. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  88078. targetIndex++;
  88079. }
  88080. sourceIndex += elementStride;
  88081. }
  88082. return targetBuffer;
  88083. };
  88084. GLTFLoader.prototype._addPendingData = function (data) {
  88085. if (!this._renderReady) {
  88086. this._renderPendingCount++;
  88087. }
  88088. this._addLoaderPendingData(data);
  88089. };
  88090. GLTFLoader.prototype._removePendingData = function (data) {
  88091. var _this = this;
  88092. if (!this._renderReady) {
  88093. if (--this._renderPendingCount === 0) {
  88094. this._addLoaderPendingData(this);
  88095. this._compileMaterialsAsync(function () {
  88096. _this._compileShadowGeneratorsAsync(function () {
  88097. _this._removeLoaderPendingData(_this);
  88098. _this._renderReady = true;
  88099. _this._onRenderReady();
  88100. });
  88101. });
  88102. }
  88103. }
  88104. this._removeLoaderPendingData(data);
  88105. };
  88106. GLTFLoader.prototype._addLoaderPendingData = function (data) {
  88107. this._loaderPendingCount++;
  88108. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  88109. var tracker = _a[_i];
  88110. tracker._addPendingData(data);
  88111. }
  88112. };
  88113. GLTFLoader.prototype._removeLoaderPendingData = function (data) {
  88114. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  88115. var tracker = _a[_i];
  88116. tracker._removePendingData(data);
  88117. }
  88118. if (--this._loaderPendingCount === 0) {
  88119. this._onComplete();
  88120. }
  88121. };
  88122. GLTFLoader.prototype._whenAction = function (action, onComplete) {
  88123. var _this = this;
  88124. var tracker = new GLTFLoaderTracker(function () {
  88125. _this._loaderTrackers.splice(_this._loaderTrackers.indexOf(tracker), 1);
  88126. onComplete();
  88127. });
  88128. this._loaderTrackers.push(tracker);
  88129. this._addLoaderPendingData(tracker);
  88130. action();
  88131. this._removeLoaderPendingData(tracker);
  88132. };
  88133. GLTFLoader.prototype._getDefaultMaterial = function () {
  88134. if (!this._defaultMaterial) {
  88135. var id = "__gltf_default";
  88136. var material = this._babylonScene.getMaterialByName(id);
  88137. if (!material) {
  88138. material = new BABYLON.PBRMaterial(id, this._babylonScene);
  88139. material.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  88140. material.sideOrientation = BABYLON.Material.ClockWiseSideOrientation;
  88141. material.metallic = 1;
  88142. material.roughness = 1;
  88143. }
  88144. this._defaultMaterial = material;
  88145. }
  88146. return this._defaultMaterial;
  88147. };
  88148. GLTFLoader.prototype._loadMaterialMetallicRoughnessProperties = function (context, material) {
  88149. var babylonMaterial = material.babylonMaterial;
  88150. // Ensure metallic workflow
  88151. babylonMaterial.metallic = 1;
  88152. babylonMaterial.roughness = 1;
  88153. var properties = material.pbrMetallicRoughness;
  88154. if (!properties) {
  88155. return;
  88156. }
  88157. babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  88158. babylonMaterial.metallic = properties.metallicFactor == null ? 1 : properties.metallicFactor;
  88159. babylonMaterial.roughness = properties.roughnessFactor == null ? 1 : properties.roughnessFactor;
  88160. if (properties.baseColorTexture) {
  88161. var texture = GLTFLoader._GetProperty(this._gltf.textures, properties.baseColorTexture.index);
  88162. if (!texture) {
  88163. throw new Error(context + ": Failed to find base color texture " + properties.baseColorTexture.index);
  88164. }
  88165. babylonMaterial.albedoTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.baseColorTexture.texCoord);
  88166. }
  88167. if (properties.metallicRoughnessTexture) {
  88168. var texture = GLTFLoader._GetProperty(this._gltf.textures, properties.metallicRoughnessTexture.index);
  88169. if (!texture) {
  88170. throw new Error(context + ": Failed to find metallic roughness texture " + properties.metallicRoughnessTexture.index);
  88171. }
  88172. babylonMaterial.metallicTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.metallicRoughnessTexture.texCoord);
  88173. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  88174. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  88175. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  88176. }
  88177. this._loadMaterialAlphaProperties(context, material, properties.baseColorFactor);
  88178. };
  88179. GLTFLoader.prototype._loadMaterial = function (context, material, assign) {
  88180. if (material.babylonMaterial) {
  88181. assign(material.babylonMaterial, false);
  88182. return;
  88183. }
  88184. if (GLTF2.GLTFLoaderExtension.LoadMaterial(this, context, material, assign)) {
  88185. return;
  88186. }
  88187. this._createPbrMaterial(material);
  88188. this._loadMaterialBaseProperties(context, material);
  88189. this._loadMaterialMetallicRoughnessProperties(context, material);
  88190. assign(material.babylonMaterial, true);
  88191. };
  88192. GLTFLoader.prototype._createPbrMaterial = function (material) {
  88193. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + material.index, this._babylonScene);
  88194. babylonMaterial.sideOrientation = BABYLON.Material.ClockWiseSideOrientation;
  88195. material.babylonMaterial = babylonMaterial;
  88196. };
  88197. GLTFLoader.prototype._loadMaterialBaseProperties = function (context, material) {
  88198. var babylonMaterial = material.babylonMaterial;
  88199. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  88200. if (material.doubleSided) {
  88201. babylonMaterial.backFaceCulling = false;
  88202. babylonMaterial.twoSidedLighting = true;
  88203. }
  88204. if (material.normalTexture) {
  88205. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.normalTexture.index);
  88206. if (!texture) {
  88207. throw new Error(context + ": Failed to find normal texture " + material.normalTexture.index);
  88208. }
  88209. babylonMaterial.bumpTexture = this._loadTexture("#/textures/" + texture.index, texture, material.normalTexture.texCoord);
  88210. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  88211. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  88212. if (material.normalTexture.scale != null) {
  88213. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  88214. }
  88215. }
  88216. if (material.occlusionTexture) {
  88217. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.occlusionTexture.index);
  88218. if (!texture) {
  88219. throw new Error(context + ": Failed to find occlusion texture " + material.occlusionTexture.index);
  88220. }
  88221. babylonMaterial.ambientTexture = this._loadTexture("#/textures/" + texture.index, texture, material.occlusionTexture.texCoord);
  88222. babylonMaterial.useAmbientInGrayScale = true;
  88223. if (material.occlusionTexture.strength != null) {
  88224. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  88225. }
  88226. }
  88227. if (material.emissiveTexture) {
  88228. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.emissiveTexture.index);
  88229. if (!texture) {
  88230. throw new Error(context + ": Failed to find emissive texture " + material.emissiveTexture.index);
  88231. }
  88232. babylonMaterial.emissiveTexture = this._loadTexture("#/textures/" + texture.index, texture, material.emissiveTexture.texCoord);
  88233. }
  88234. };
  88235. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, colorFactor) {
  88236. var babylonMaterial = material.babylonMaterial;
  88237. var alphaMode = material.alphaMode || "OPAQUE";
  88238. switch (alphaMode) {
  88239. case "OPAQUE": {
  88240. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  88241. break;
  88242. }
  88243. case "MASK": {
  88244. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  88245. babylonMaterial.alphaCutOff = (material.alphaCutoff == null ? 0.5 : material.alphaCutoff);
  88246. if (colorFactor) {
  88247. if (colorFactor[3] == 0) {
  88248. babylonMaterial.alphaCutOff = 1;
  88249. }
  88250. else {
  88251. babylonMaterial.alphaCutOff /= colorFactor[3];
  88252. }
  88253. }
  88254. if (babylonMaterial.albedoTexture) {
  88255. babylonMaterial.albedoTexture.hasAlpha = true;
  88256. }
  88257. break;
  88258. }
  88259. case "BLEND": {
  88260. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  88261. if (colorFactor) {
  88262. babylonMaterial.alpha = colorFactor[3];
  88263. }
  88264. if (babylonMaterial.albedoTexture) {
  88265. babylonMaterial.albedoTexture.hasAlpha = true;
  88266. babylonMaterial.useAlphaFromAlbedoTexture = true;
  88267. }
  88268. break;
  88269. }
  88270. default: {
  88271. throw new Error(context + ": Invalid alpha mode " + material.alphaMode);
  88272. }
  88273. }
  88274. };
  88275. GLTFLoader.prototype._loadTexture = function (context, texture, coordinatesIndex) {
  88276. var _this = this;
  88277. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(this._gltf.samplers, texture.sampler));
  88278. if (!sampler) {
  88279. throw new Error(context + ": Failed to find sampler " + texture.sampler);
  88280. }
  88281. this._loadSampler("#/samplers/" + sampler.index, sampler);
  88282. this._addPendingData(texture);
  88283. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, sampler.noMipMaps, false, sampler.samplingMode, function () {
  88284. _this._tryCatchOnError(function () {
  88285. _this._removePendingData(texture);
  88286. });
  88287. }, function (message) {
  88288. _this._tryCatchOnError(function () {
  88289. throw new Error(context + ": " + message);
  88290. });
  88291. });
  88292. if (texture.url) {
  88293. babylonTexture.updateURL(texture.url);
  88294. }
  88295. else if (texture.dataReadyObservable) {
  88296. texture.dataReadyObservable.add(function (texture) {
  88297. babylonTexture.updateURL(texture.url);
  88298. });
  88299. }
  88300. else {
  88301. texture.dataReadyObservable = new BABYLON.Observable();
  88302. texture.dataReadyObservable.add(function (texture) {
  88303. babylonTexture.updateURL(texture.url);
  88304. });
  88305. var image_1 = GLTFLoader._GetProperty(this._gltf.images, texture.source);
  88306. if (!image_1) {
  88307. throw new Error(context + ": Failed to find source " + texture.source);
  88308. }
  88309. this._loadImageAsync("#/images/" + image_1.index, image_1, function (data) {
  88310. texture.url = URL.createObjectURL(new Blob([data], { type: image_1.mimeType }));
  88311. texture.dataReadyObservable.notifyObservers(texture);
  88312. texture.dataReadyObservable = undefined;
  88313. });
  88314. }
  88315. babylonTexture.coordinatesIndex = coordinatesIndex || 0;
  88316. babylonTexture.wrapU = sampler.wrapU;
  88317. babylonTexture.wrapV = sampler.wrapV;
  88318. babylonTexture.name = texture.name || "texture" + texture.index;
  88319. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  88320. return babylonTexture;
  88321. };
  88322. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  88323. if (sampler.noMipMaps != undefined) {
  88324. return;
  88325. }
  88326. sampler.noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  88327. sampler.samplingMode = GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter);
  88328. sampler.wrapU = GLTFLoader._GetTextureWrapMode(context, sampler.wrapS);
  88329. sampler.wrapV = GLTFLoader._GetTextureWrapMode(context, sampler.wrapT);
  88330. };
  88331. GLTFLoader.prototype._loadImageAsync = function (context, image, onSuccess) {
  88332. if (image.uri) {
  88333. this._loadUriAsync(context, image.uri, onSuccess);
  88334. }
  88335. else {
  88336. var bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, image.bufferView);
  88337. if (!bufferView) {
  88338. throw new Error(context + ": Failed to find buffer view " + image.bufferView);
  88339. }
  88340. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, onSuccess);
  88341. }
  88342. };
  88343. GLTFLoader.prototype._loadUriAsync = function (context, uri, onSuccess) {
  88344. var _this = this;
  88345. if (GLTF2.GLTFUtils.IsBase64(uri)) {
  88346. onSuccess(new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(uri)));
  88347. return;
  88348. }
  88349. if (!GLTF2.GLTFUtils.ValidateUri(uri)) {
  88350. throw new Error(context + ": Uri '" + uri + "' is invalid");
  88351. }
  88352. var request = BABYLON.Tools.LoadFile(this._rootUrl + uri, function (data) {
  88353. _this._tryCatchOnError(function () {
  88354. onSuccess(new Uint8Array(data));
  88355. });
  88356. }, function (event) {
  88357. _this._tryCatchOnError(function () {
  88358. if (request && !_this._renderReady) {
  88359. request._lengthComputable = event.lengthComputable;
  88360. request._loaded = event.loaded;
  88361. request._total = event.total;
  88362. _this._onProgress();
  88363. }
  88364. });
  88365. }, this._babylonScene.database, true, function (request, exception) {
  88366. _this._tryCatchOnError(function () {
  88367. throw new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request);
  88368. });
  88369. });
  88370. this._requests.push(request);
  88371. };
  88372. GLTFLoader.prototype._tryCatchOnError = function (handler) {
  88373. if (this._disposed) {
  88374. return;
  88375. }
  88376. try {
  88377. handler();
  88378. }
  88379. catch (e) {
  88380. BABYLON.Tools.Error("glTF Loader: " + e.message);
  88381. if (this._errorCallback) {
  88382. this._errorCallback(e.message, e);
  88383. }
  88384. this.dispose();
  88385. }
  88386. };
  88387. GLTFLoader._AssignIndices = function (array) {
  88388. if (array) {
  88389. for (var index = 0; index < array.length; index++) {
  88390. array[index].index = index;
  88391. }
  88392. }
  88393. };
  88394. GLTFLoader._GetProperty = function (array, index) {
  88395. if (!array || index == undefined || !array[index]) {
  88396. return null;
  88397. }
  88398. return array[index];
  88399. };
  88400. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  88401. // Set defaults if undefined
  88402. mode = mode == undefined ? GLTF2.ETextureWrapMode.REPEAT : mode;
  88403. switch (mode) {
  88404. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  88405. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  88406. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  88407. default:
  88408. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode " + mode);
  88409. return BABYLON.Texture.WRAP_ADDRESSMODE;
  88410. }
  88411. };
  88412. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  88413. // Set defaults if undefined
  88414. magFilter = magFilter == undefined ? GLTF2.ETextureMagFilter.LINEAR : magFilter;
  88415. minFilter = minFilter == undefined ? GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR : minFilter;
  88416. if (magFilter === GLTF2.ETextureMagFilter.LINEAR) {
  88417. switch (minFilter) {
  88418. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.LINEAR_NEAREST;
  88419. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.LINEAR_LINEAR;
  88420. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  88421. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  88422. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  88423. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  88424. default:
  88425. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  88426. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  88427. }
  88428. }
  88429. else {
  88430. if (magFilter !== GLTF2.ETextureMagFilter.NEAREST) {
  88431. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter " + magFilter);
  88432. }
  88433. switch (minFilter) {
  88434. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.NEAREST_NEAREST;
  88435. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.NEAREST_LINEAR;
  88436. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  88437. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  88438. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  88439. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  88440. default:
  88441. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  88442. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  88443. }
  88444. }
  88445. };
  88446. GLTFLoader._GetNumComponents = function (context, type) {
  88447. switch (type) {
  88448. case "SCALAR": return 1;
  88449. case "VEC2": return 2;
  88450. case "VEC3": return 3;
  88451. case "VEC4": return 4;
  88452. case "MAT2": return 4;
  88453. case "MAT3": return 9;
  88454. case "MAT4": return 16;
  88455. }
  88456. throw new Error(context + ": Invalid type " + type);
  88457. };
  88458. GLTFLoader.prototype._compileMaterialAsync = function (babylonMaterial, babylonMesh, onSuccess) {
  88459. var _this = this;
  88460. if (this.useClipPlane) {
  88461. babylonMaterial.forceCompilation(babylonMesh, function () {
  88462. babylonMaterial.forceCompilation(babylonMesh, function () {
  88463. _this._tryCatchOnError(onSuccess);
  88464. }, { clipPlane: true });
  88465. });
  88466. }
  88467. else {
  88468. babylonMaterial.forceCompilation(babylonMesh, function () {
  88469. _this._tryCatchOnError(onSuccess);
  88470. });
  88471. }
  88472. };
  88473. GLTFLoader.prototype._compileMaterialsAsync = function (onSuccess) {
  88474. if (!this.compileMaterials || !this._gltf.materials) {
  88475. onSuccess();
  88476. return;
  88477. }
  88478. var meshes = this._getMeshes();
  88479. var remaining = 0;
  88480. for (var _i = 0, meshes_1 = meshes; _i < meshes_1.length; _i++) {
  88481. var mesh = meshes_1[_i];
  88482. if (mesh.material instanceof BABYLON.MultiMaterial) {
  88483. for (var _a = 0, _b = mesh.material.subMaterials; _a < _b.length; _a++) {
  88484. var subMaterial = _b[_a];
  88485. if (subMaterial) {
  88486. remaining++;
  88487. }
  88488. }
  88489. }
  88490. else if (mesh.material) {
  88491. remaining++;
  88492. }
  88493. }
  88494. if (remaining === 0) {
  88495. onSuccess();
  88496. return;
  88497. }
  88498. for (var _c = 0, meshes_2 = meshes; _c < meshes_2.length; _c++) {
  88499. var mesh = meshes_2[_c];
  88500. if (mesh.material instanceof BABYLON.MultiMaterial) {
  88501. for (var _d = 0, _e = mesh.material.subMaterials; _d < _e.length; _d++) {
  88502. var subMaterial = _e[_d];
  88503. if (subMaterial) {
  88504. this._compileMaterialAsync(subMaterial, mesh, function () {
  88505. if (--remaining === 0) {
  88506. onSuccess();
  88507. }
  88508. });
  88509. }
  88510. }
  88511. }
  88512. else if (mesh.material) {
  88513. this._compileMaterialAsync(mesh.material, mesh, function () {
  88514. if (--remaining === 0) {
  88515. onSuccess();
  88516. }
  88517. });
  88518. }
  88519. }
  88520. };
  88521. GLTFLoader.prototype._compileShadowGeneratorsAsync = function (onSuccess) {
  88522. var _this = this;
  88523. if (!this.compileShadowGenerators) {
  88524. onSuccess();
  88525. return;
  88526. }
  88527. var lights = this._babylonScene.lights;
  88528. var remaining = 0;
  88529. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  88530. var light = lights_1[_i];
  88531. var generator = light.getShadowGenerator();
  88532. if (generator) {
  88533. remaining++;
  88534. }
  88535. }
  88536. if (remaining === 0) {
  88537. onSuccess();
  88538. return;
  88539. }
  88540. for (var _a = 0, lights_2 = lights; _a < lights_2.length; _a++) {
  88541. var light = lights_2[_a];
  88542. var generator = light.getShadowGenerator();
  88543. if (generator) {
  88544. generator.forceCompilation(function () {
  88545. if (--remaining === 0) {
  88546. _this._tryCatchOnError(onSuccess);
  88547. }
  88548. });
  88549. }
  88550. }
  88551. };
  88552. GLTFLoader.prototype._abortRequests = function () {
  88553. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  88554. var request = _a[_i];
  88555. request.abort();
  88556. }
  88557. this._requests.length = 0;
  88558. };
  88559. GLTFLoader.prototype._releaseResources = function () {
  88560. if (this._gltf.textures) {
  88561. for (var _i = 0, _a = this._gltf.textures; _i < _a.length; _i++) {
  88562. var texture = _a[_i];
  88563. if (texture.url) {
  88564. URL.revokeObjectURL(texture.url);
  88565. texture.url = undefined;
  88566. }
  88567. }
  88568. }
  88569. };
  88570. GLTFLoader.Extensions = {};
  88571. return GLTFLoader;
  88572. }());
  88573. GLTF2.GLTFLoader = GLTFLoader;
  88574. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  88575. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  88576. })(BABYLON || (BABYLON = {}));
  88577. //# sourceMappingURL=babylon.glTFLoader.js.map
  88578. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  88579. var BABYLON;
  88580. (function (BABYLON) {
  88581. var GLTF2;
  88582. (function (GLTF2) {
  88583. /**
  88584. * Utils functions for GLTF
  88585. */
  88586. var GLTFUtils = /** @class */ (function () {
  88587. function GLTFUtils() {
  88588. }
  88589. /**
  88590. * If the uri is a base64 string
  88591. * @param uri: the uri to test
  88592. */
  88593. GLTFUtils.IsBase64 = function (uri) {
  88594. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  88595. };
  88596. /**
  88597. * Decode the base64 uri
  88598. * @param uri: the uri to decode
  88599. */
  88600. GLTFUtils.DecodeBase64 = function (uri) {
  88601. var decodedString = atob(uri.split(",")[1]);
  88602. var bufferLength = decodedString.length;
  88603. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  88604. for (var i = 0; i < bufferLength; i++) {
  88605. bufferView[i] = decodedString.charCodeAt(i);
  88606. }
  88607. return bufferView.buffer;
  88608. };
  88609. GLTFUtils.ValidateUri = function (uri) {
  88610. return (uri.indexOf("..") === -1);
  88611. };
  88612. return GLTFUtils;
  88613. }());
  88614. GLTF2.GLTFUtils = GLTFUtils;
  88615. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  88616. })(BABYLON || (BABYLON = {}));
  88617. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  88618. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  88619. var BABYLON;
  88620. (function (BABYLON) {
  88621. var GLTF2;
  88622. (function (GLTF2) {
  88623. var GLTFLoaderExtension = /** @class */ (function () {
  88624. function GLTFLoaderExtension() {
  88625. this.enabled = true;
  88626. }
  88627. GLTFLoaderExtension.prototype._traverseNode = function (loader, context, node, action, parentNode) { return false; };
  88628. GLTFLoaderExtension.prototype._loadNode = function (loader, context, node) { return false; };
  88629. GLTFLoaderExtension.prototype._loadMaterial = function (loader, context, material, assign) { return false; };
  88630. GLTFLoaderExtension.prototype._loadExtension = function (context, property, action) {
  88631. var _this = this;
  88632. if (!property.extensions) {
  88633. return false;
  88634. }
  88635. var extension = property.extensions[this.name];
  88636. if (!extension) {
  88637. return false;
  88638. }
  88639. // Clear out the extension before executing the action to avoid recursing into the same property.
  88640. property.extensions[this.name] = undefined;
  88641. action(context + "extensions/" + this.name, extension, function () {
  88642. // Restore the extension after completing the action.
  88643. property.extensions[_this.name] = extension;
  88644. });
  88645. return true;
  88646. };
  88647. GLTFLoaderExtension.TraverseNode = function (loader, context, node, action, parentNode) {
  88648. return this._ApplyExtensions(function (extension) { return extension._traverseNode(loader, context, node, action, parentNode); });
  88649. };
  88650. GLTFLoaderExtension.LoadNode = function (loader, context, node) {
  88651. return this._ApplyExtensions(function (extension) { return extension._loadNode(loader, context, node); });
  88652. };
  88653. GLTFLoaderExtension.LoadMaterial = function (loader, context, material, assign) {
  88654. return this._ApplyExtensions(function (extension) { return extension._loadMaterial(loader, context, material, assign); });
  88655. };
  88656. GLTFLoaderExtension._ApplyExtensions = function (action) {
  88657. var extensions = GLTFLoaderExtension._Extensions;
  88658. if (!extensions) {
  88659. return false;
  88660. }
  88661. for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) {
  88662. var extension = extensions_1[_i];
  88663. if (extension.enabled && action(extension)) {
  88664. return true;
  88665. }
  88666. }
  88667. return false;
  88668. };
  88669. //
  88670. // Utilities
  88671. //
  88672. GLTFLoaderExtension._Extensions = [];
  88673. return GLTFLoaderExtension;
  88674. }());
  88675. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  88676. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  88677. })(BABYLON || (BABYLON = {}));
  88678. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  88679. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  88680. var BABYLON;
  88681. (function (BABYLON) {
  88682. var GLTF2;
  88683. (function (GLTF2) {
  88684. var Extensions;
  88685. (function (Extensions) {
  88686. // See https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod for more information about this extension.
  88687. var MSFTLOD = /** @class */ (function (_super) {
  88688. __extends(MSFTLOD, _super);
  88689. function MSFTLOD() {
  88690. var _this = _super !== null && _super.apply(this, arguments) || this;
  88691. /**
  88692. * Specify the minimal delay between LODs in ms (default = 250)
  88693. */
  88694. _this.Delay = 250;
  88695. return _this;
  88696. }
  88697. Object.defineProperty(MSFTLOD.prototype, "name", {
  88698. get: function () {
  88699. return "MSFT_lod";
  88700. },
  88701. enumerable: true,
  88702. configurable: true
  88703. });
  88704. MSFTLOD.prototype._traverseNode = function (loader, context, node, action, parentNode) {
  88705. return this._loadExtension(context, node, function (context, extension, onComplete) {
  88706. for (var i = extension.ids.length - 1; i >= 0; i--) {
  88707. var lodNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, extension.ids[i]);
  88708. if (!lodNode) {
  88709. throw new Error(context + ": Failed to find node " + extension.ids[i]);
  88710. }
  88711. loader._traverseNode(context, lodNode, action, parentNode);
  88712. }
  88713. loader._traverseNode(context, node, action, parentNode);
  88714. onComplete();
  88715. });
  88716. };
  88717. MSFTLOD.prototype._loadNode = function (loader, context, node) {
  88718. var _this = this;
  88719. return this._loadExtension(context, node, function (context, extension, onComplete) {
  88720. var nodes = [node];
  88721. for (var _i = 0, _a = extension.ids; _i < _a.length; _i++) {
  88722. var index = _a[_i];
  88723. var lodNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, index);
  88724. if (!lodNode) {
  88725. throw new Error(context + ": Failed to find node " + index);
  88726. }
  88727. nodes.push(lodNode);
  88728. }
  88729. loader._addLoaderPendingData(node);
  88730. _this._loadNodeLOD(loader, context, nodes, nodes.length - 1, function () {
  88731. loader._removeLoaderPendingData(node);
  88732. onComplete();
  88733. });
  88734. });
  88735. };
  88736. MSFTLOD.prototype._loadNodeLOD = function (loader, context, nodes, index, onComplete) {
  88737. var _this = this;
  88738. loader._whenAction(function () {
  88739. loader._loadNode(context, nodes[index]);
  88740. }, function () {
  88741. if (index !== nodes.length - 1) {
  88742. var previousNode = nodes[index + 1];
  88743. previousNode.babylonMesh.setEnabled(false);
  88744. }
  88745. if (index === 0) {
  88746. onComplete();
  88747. return;
  88748. }
  88749. setTimeout(function () {
  88750. loader._tryCatchOnError(function () {
  88751. _this._loadNodeLOD(loader, context, nodes, index - 1, onComplete);
  88752. });
  88753. }, _this.Delay);
  88754. });
  88755. };
  88756. MSFTLOD.prototype._loadMaterial = function (loader, context, material, assign) {
  88757. var _this = this;
  88758. return this._loadExtension(context, material, function (context, extension, onComplete) {
  88759. var materials = [material];
  88760. for (var _i = 0, _a = extension.ids; _i < _a.length; _i++) {
  88761. var index = _a[_i];
  88762. var lodMaterial = GLTF2.GLTFLoader._GetProperty(loader._gltf.materials, index);
  88763. if (!lodMaterial) {
  88764. throw new Error(context + ": Failed to find material " + index);
  88765. }
  88766. materials.push(lodMaterial);
  88767. }
  88768. loader._addLoaderPendingData(material);
  88769. _this._loadMaterialLOD(loader, context, materials, materials.length - 1, assign, function () {
  88770. loader._removeLoaderPendingData(material);
  88771. onComplete();
  88772. });
  88773. });
  88774. };
  88775. MSFTLOD.prototype._loadMaterialLOD = function (loader, context, materials, index, assign, onComplete) {
  88776. var _this = this;
  88777. loader._loadMaterial(context, materials[index], function (babylonMaterial, isNew) {
  88778. if (index === materials.length - 1) {
  88779. assign(babylonMaterial, isNew);
  88780. // Load the next LOD when the loader is ready to render.
  88781. loader._executeWhenRenderReady(function () {
  88782. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  88783. });
  88784. }
  88785. else {
  88786. BABYLON.BaseTexture.WhenAllReady(babylonMaterial.getActiveTextures(), function () {
  88787. assign(babylonMaterial, isNew);
  88788. if (index === 0) {
  88789. onComplete();
  88790. }
  88791. else {
  88792. setTimeout(function () {
  88793. loader._tryCatchOnError(function () {
  88794. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  88795. });
  88796. }, _this.Delay);
  88797. }
  88798. });
  88799. }
  88800. });
  88801. };
  88802. return MSFTLOD;
  88803. }(GLTF2.GLTFLoaderExtension));
  88804. Extensions.MSFTLOD = MSFTLOD;
  88805. GLTF2.GLTFLoader.RegisterExtension(new MSFTLOD());
  88806. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  88807. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  88808. })(BABYLON || (BABYLON = {}));
  88809. //# sourceMappingURL=MSFT_lod.js.map
  88810. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  88811. var BABYLON;
  88812. (function (BABYLON) {
  88813. var GLTF2;
  88814. (function (GLTF2) {
  88815. var Extensions;
  88816. (function (Extensions) {
  88817. var KHRMaterialsPbrSpecularGlossiness = /** @class */ (function (_super) {
  88818. __extends(KHRMaterialsPbrSpecularGlossiness, _super);
  88819. function KHRMaterialsPbrSpecularGlossiness() {
  88820. return _super !== null && _super.apply(this, arguments) || this;
  88821. }
  88822. Object.defineProperty(KHRMaterialsPbrSpecularGlossiness.prototype, "name", {
  88823. get: function () {
  88824. return "KHR_materials_pbrSpecularGlossiness";
  88825. },
  88826. enumerable: true,
  88827. configurable: true
  88828. });
  88829. KHRMaterialsPbrSpecularGlossiness.prototype._loadMaterial = function (loader, context, material, assign) {
  88830. var _this = this;
  88831. return this._loadExtension(context, material, function (context, extension, onComplete) {
  88832. loader._createPbrMaterial(material);
  88833. loader._loadMaterialBaseProperties(context, material);
  88834. _this._loadSpecularGlossinessProperties(loader, context, material, extension);
  88835. assign(material.babylonMaterial, true);
  88836. onComplete();
  88837. });
  88838. };
  88839. KHRMaterialsPbrSpecularGlossiness.prototype._loadSpecularGlossinessProperties = function (loader, context, material, properties) {
  88840. var babylonMaterial = material.babylonMaterial;
  88841. babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  88842. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  88843. babylonMaterial.microSurface = properties.glossinessFactor == null ? 1 : properties.glossinessFactor;
  88844. if (properties.diffuseTexture) {
  88845. var texture = GLTF2.GLTFLoader._GetProperty(loader._gltf.textures, properties.diffuseTexture.index);
  88846. if (!texture) {
  88847. throw new Error(context + ": Failed to find diffuse texture " + properties.diffuseTexture.index);
  88848. }
  88849. babylonMaterial.albedoTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.diffuseTexture.texCoord);
  88850. }
  88851. if (properties.specularGlossinessTexture) {
  88852. var texture = GLTF2.GLTFLoader._GetProperty(loader._gltf.textures, properties.specularGlossinessTexture.index);
  88853. if (!texture) {
  88854. throw new Error(context + ": Failed to find diffuse texture " + properties.specularGlossinessTexture.index);
  88855. }
  88856. babylonMaterial.reflectivityTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.specularGlossinessTexture.texCoord);
  88857. babylonMaterial.reflectivityTexture.hasAlpha = true;
  88858. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  88859. }
  88860. loader._loadMaterialAlphaProperties(context, material, properties.diffuseFactor);
  88861. };
  88862. return KHRMaterialsPbrSpecularGlossiness;
  88863. }(GLTF2.GLTFLoaderExtension));
  88864. Extensions.KHRMaterialsPbrSpecularGlossiness = KHRMaterialsPbrSpecularGlossiness;
  88865. GLTF2.GLTFLoader.RegisterExtension(new KHRMaterialsPbrSpecularGlossiness());
  88866. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  88867. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  88868. })(BABYLON || (BABYLON = {}));
  88869. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  88870. (function universalModuleDefinition(root, factory) {
  88871. var f = factory();
  88872. if (root && root["BABYLON"]) {
  88873. return;
  88874. }
  88875. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  88876. globalObject["BABYLON"] = f;
  88877. if(typeof exports === 'object' && typeof module === 'object')
  88878. module.exports = f;
  88879. else if(typeof define === 'function' && define.amd)
  88880. define(["BABYLON"], factory);
  88881. else if(typeof exports === 'object')
  88882. exports["BABYLON"] = f;
  88883. else {
  88884. root["BABYLON"] = f;
  88885. }
  88886. })(this, function() {
  88887. return BABYLON;
  88888. });